package com.xyz.service.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.DateUnit;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.NumberUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.xyz.config.SystemData;
import com.xyz.dao.mapper.BusinessFileDaoMapper;
import com.xyz.dao.pojo.BusinessFileVo;
import com.xyz.dto.RepairMaintenanceDto;
import com.xyz.dto.RepairMaintenanceInsDto;
import com.xyz.dto.RepairWorkOrderDto;
import com.xyz.dto.SelectPageAllDto;
import com.xyz.dto.enums.EnumAcceptBusinessType;
import com.xyz.dto.enums.EnumAnnBusinessType;
import com.xyz.dto.enums.EnumBusinessType;
import com.xyz.entity.mapper.*;
import com.xyz.entity.pojo.*;
import com.xyz.service.CommonService;
import com.xyz.service.EquipmentTreeService;
import com.xyz.service.RepairService;
import com.xyz.util.dto.DataResult;
import com.xyz.util.dto.GridData;
import com.xyz.util.dto.LoginInfo;
import com.xyz.dto.enums.EnumRepState;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

@Service
@Transactional(rollbackFor = Exception.class)
public class RepairServiceImpl implements RepairService {

    @Autowired
    private CommonService commonService;

    @Autowired
    private RepairWorkOrderMapper repairWorkOrderMapper;

    @Autowired
    private RepairMaintenanceMapper repairMaintenanceMapper;

    @Autowired
    private RepairMaintenanceSuspendMapper repairMaintenanceSuspendMapper;

    @Autowired
    private BusinessAnnounceMapper businessAnnounceMapper;

    @Autowired
    private BusinessAcceptMapper businessAcceptMapper;

    @Autowired
    private BusinessFileMapper businessFileMapper;

    @Autowired
    private EquipmentInfoMapper equipmentInfoMapper;

    @Autowired
    private RepairWorkOrderFlowMapper repairWorkOrderFlowMapper;

    @Autowired
    private UpkeepWorkOrderMapper upkeepWorkOrderMapper;

    @Autowired
    private UpkeepMaintenanceMapper upkeepMaintenanceMapper;

    @Autowired
    private BusinessFileDaoMapper businessFileDao;

    @Autowired
    private SystemUserMapper systemUserMapper;

    @Autowired
    private SystemEmployeeMapper systemEmployeeMapper;

    @Autowired
    private SystemRoleMapper systemRoleMapper;

    @Autowired
    private EquipmentTreeService equipmentTreeService;

    @Autowired
    private EquipmentTreeMapper equipmentTreeMapper;

    /*
     * 根据权限查询维修单数据
     *
     * */
    @Override
    public DataResult selectRepairAll(LoginInfo loginInfo, SelectPageAllDto selectPageAllDto) throws Exception {
        Page<RepairWorkOrder> pageObject = PageHelper.startPage(NumberUtil.parseInt(selectPageAllDto.getPageNum()), NumberUtil.parseInt(selectPageAllDto.getPageSize()));
        //获取数据
        List<RepairWorkOrder> repairWorkOrderAll = commonService.getRepairWorkOrderAll(loginInfo, selectPageAllDto);
        List<Map<String, Object>> list = new ArrayList<>();
        for (RepairWorkOrder rw : repairWorkOrderAll) {
            Map<String, Object> map = new HashMap<>();
            map.put("repId", rw.getRepId());
            map.put("workOrderCode", rw.getWorkOrderCode());
            map.put("employeeName", commonService.getEmployeeNameById(rw.getEmployeeId()));
            map.put("repDesc", rw.getRepDesc());
            map.put("emName", rw.getEmName());
            map.put("repState", rw.getRepState());
            map.put("urgencyLevel", rw.getUrgencyLevel());
            map.put("repFaultType", rw.getRepFaultType());
            map.put("emSpecification", rw.getEmSpecification());
            map.put("emLocation", rw.getEmLocation());
            map.put("repStartTime", rw.getRepStartTime());
            map.put("repEmState", rw.getRepEmState());
            map.put("emStateDesc", rw.getEmStateDesc());
            list.add(map);
        }
        //分页总数
        GridData gridData = new GridData(pageObject.getTotal(), list);
        return DataResult.build9100(gridData);
    }

    /*
     * 根据设备查询
     * */
    @Override
    public DataResult getRepairAllByEqId(LoginInfo loginInfo, SelectPageAllDto selectPageAllDto) throws Exception {
        Page<RepairWorkOrder> pageObject = PageHelper.startPage(NumberUtil.parseInt(selectPageAllDto.getPageNum()), NumberUtil.parseInt(selectPageAllDto.getPageSize()));
        //获取数据
        RepairWorkOrderExample tExample = new RepairWorkOrderExample();
        RepairWorkOrderExample.Criteria repCriteria = tExample.createCriteria();

        if (StrUtil.isBlank(selectPageAllDto.getEmId())) {
            return DataResult.build9200("emId数据缺失");
        }
        //故障类别
        Map<Integer, String> faultTypeMap = commonService.getDictMap("TYPE_REP_FAULT");
        //故障原因
        Map<Integer, String> reasonMap = commonService.getDictMap("TYPE_REP_REASON");
        //设备状态
        Map<Integer, String> emStateMap = commonService.getDictMap("TYPE_EM_STATE");


        repCriteria.andEmIdEqualTo(Long.parseLong(selectPageAllDto.getEmId()));
        tExample.setOrderByClause("create_time desc");
        List<RepairWorkOrder> repairList = repairWorkOrderMapper.selectByExample(tExample);
        List<Map<String, Object>> list = new ArrayList<>();
        for (RepairWorkOrder rw : repairList) {
            List<Integer> notInStatus = Arrays.asList(EnumRepState.INVALID.getRepState(), EnumRepState.PENDING_ANNOUNCE.getRepState(),
                    EnumRepState.PENDING_RECEIVE.getRepState(),
                    EnumRepState.PENDING_REFUSE.getRepState(),
                    EnumRepState.PENDING_TRANSFER.getRepState());
            RepairMaintenanceExample repMainExample = new RepairMaintenanceExample();
            RepairMaintenanceExample.Criteria repMainCriteria = repMainExample.createCriteria();
            repMainCriteria.andRepIdEqualTo(rw.getRepId());
            repMainCriteria.andMtcStateNotIn(notInStatus);
            repMainExample.setOrderByClause("create_time desc limit 1");
            List<RepairMaintenance> repairMaintenanceList = repairMaintenanceMapper.selectByExample(repMainExample);
            RepairMaintenance repairMaintenance = new RepairMaintenance();
            if (CollUtil.isNotEmpty(repairMaintenanceList)) {
                repairMaintenance = repairMaintenanceList.get(0);
            }
            Map<String, Object> map = new HashMap<>();
            map.put("repId", rw.getRepId());
            map.put("workOrderCode", rw.getWorkOrderCode());
            map.put("employeeName", commonService.getEmployeeNameById(rw.getEmployeeId()));
            map.put("repDesc", repairMaintenance.getMtcDesc());
            map.put("emName", rw.getEmName());
            map.put("repState", rw.getRepState());
            map.put("urgencyLevel", rw.getUrgencyLevel());
            map.put("repFaultType", rw.getRepFaultType());
            map.put("createTime", DateUtil.format(rw.getCreateTime(), "yyyy-MM-dd HH:mm:ss"));
            map.put("repFaultTypeName", faultTypeMap.get(rw.getRepFaultType()));
            map.put("deviceLocationAndLocationName", rw.getEmLocation()+"-"+rw.getEmName());
            map.put("faultReasonNameAndFaultTypeName", reasonMap.getOrDefault(repairMaintenance.getMtcFaultReason(), "")+"-"+faultTypeMap.getOrDefault(repairMaintenance.getMtcFaultType(), ""));
            map.put("mtcEndTime", DateUtil.format(repairMaintenance.getMtcEndTime(), "yyyy-MM-dd HH:mm:ss"));
            getRepairFileList(map, rw.getRepId());

            list.add(map);
        }
        //分页总数
        GridData gridData = new GridData(pageObject.getTotal(), list);
        return DataResult.build9100(gridData);
    }

    /*
     * 报修
     * */
    @Override
    public DataResult insertRepair(LoginInfo loginInfo, RepairWorkOrderDto repairDto) throws Exception {
        RepairWorkOrder repairWorkOrder = getNewRepairWorkOrder(repairDto);
        long emId = Long.parseLong(repairDto.getEmId());
        if (emId == 0) {
            if (StrUtil.isBlank(repairDto.getEmLocation())) {
                return DataResult.build9200("选择其他设备时,设备位置需要填写！");
            }
            repairWorkOrder.setTreeId(0L);
            repairWorkOrder.setTreeName("");
        } else {
            EquipmentTree EquipmentTree2 = commonService.getTree2ByEmId(emId);
            if(EquipmentTree2 != null){
                repairWorkOrder.setTreeId(EquipmentTree2.getId());
                repairWorkOrder.setTreeName(EquipmentTree2.getName());
            }
        }
        repairWorkOrder.setEmId(emId);
        repairWorkOrder.setEmName(repairDto.getEmName());
        if (StrUtil.isNotBlank(repairDto.getEmCode())) {
            repairWorkOrder.setEmCode(repairDto.getEmCode());
        } else {
            repairWorkOrder.setEmCode("");
        }

        if (StrUtil.isNotBlank(repairDto.getEmSpecification())) {
            repairWorkOrder.setEmSpecification(repairDto.getEmSpecification());
        } else {
            repairWorkOrder.setEmSpecification("");
        }

        if (StrUtil.isNotBlank(repairDto.getEmLocation())) {
            repairWorkOrder.setEmLocation(repairDto.getEmLocation());
        } else {
            repairWorkOrder.setEmLocation("");
        }

        if (ObjectUtil.isNotEmpty(repairDto.getMaintenanceCategoriesCode())) {
            repairWorkOrder.setMaintenanceCategories(Integer.parseInt(repairDto.getMaintenanceCategoriesCode()));
        } else {
            repairWorkOrder.setMaintenanceCategories(0);
        }

        repairWorkOrder.setEmployeeId(loginInfo.getLoginEmployeeId());
        //从维保和巡检跳转过来的报修
        if (StrUtil.isNotBlank(repairDto.getSourceCode()) && StrUtil.isNotBlank(repairDto.getSourceType())) {
            int sourceTyp = Integer.parseInt(repairDto.getSourceType());
            repairWorkOrder.setSourceCode(repairDto.getSourceCode());
            repairWorkOrder.setSourceType(sourceTyp);
        }

        int i = repairWorkOrderMapper.insertSelective(repairWorkOrder);
        //图片
        String filePicCode = repairDto.getFilePicCode();
        //音频
        String fileAudioCode = repairDto.getFileAudioCode();
        //视频
        String fileVideoCode = repairDto.getFileVideoCode();
/*        BusinessFileExample fileExample = new BusinessFileExample();
        BusinessFileExample.Criteria fileCriteria = fileExample.createCriteria();
        fileCriteria.andBusTablesIdEqualTo(repairWorkOrder.getRepId());
        fileCriteria.andBusTypeEqualTo(EnumBusinessType.REPAIR.getBusType());
        businessFileMapper.deleteByExample(fileExample);*/
        if (StrUtil.isNotBlank(filePicCode)) {
            if (filePicCode.contains(",")) {
                String[] split = filePicCode.split(",");
                for (String spFilePicCode : split) {
                    insertWorkOrderFile(repairWorkOrder.getRepId(), loginInfo.getLoginEmployeeId(), spFilePicCode, EnumBusinessType.REPAIR.getBusType(), 1, 1);
                }
            } else {
                insertWorkOrderFile(repairWorkOrder.getRepId(), loginInfo.getLoginEmployeeId(), filePicCode, EnumBusinessType.REPAIR.getBusType(), 1, 1);

            }
        }
        if (StrUtil.isNotBlank(fileAudioCode)) {
            if (fileAudioCode.contains(",")) {
                String[] split = fileAudioCode.split(",");
                for (String spFileAudioCode : split) {
                    insertWorkOrderFile(repairWorkOrder.getRepId(), loginInfo.getLoginEmployeeId(), spFileAudioCode, EnumBusinessType.REPAIR.getBusType(), 1, 2);
                }
            } else {
                insertWorkOrderFile(repairWorkOrder.getRepId(), loginInfo.getLoginEmployeeId(), fileAudioCode, EnumBusinessType.REPAIR.getBusType(), 1, 2);
            }

        }
        if (StrUtil.isNotBlank(fileVideoCode)) {
            if (fileVideoCode.contains(",")) {
                String[] split = fileVideoCode.split(",");
                for (String spFileVideoCode : split) {
                    insertWorkOrderFile(repairWorkOrder.getRepId(), loginInfo.getLoginEmployeeId(), spFileVideoCode, EnumBusinessType.REPAIR.getBusType(), 1, 3);
                }
            } else {
                insertWorkOrderFile(repairWorkOrder.getRepId(), loginInfo.getLoginEmployeeId(), fileVideoCode, EnumBusinessType.REPAIR.getBusType(), 1, 3);

            }
        }
        if (i == 0) {
            return DataResult.build9250("维修工单创建失败!!");
        }

        insertFlow(repairWorkOrder.getRepId(), loginInfo.getLoginEmployeeId(), 1, repairWorkOrder.getRepId(), EnumRepState.PENDING_ANNOUNCE.getRepState(), "创建报修");

        List<Long> userIdList = commonService.selectManagerUserIdList(2);

        String content = emId == 0 ? "【" + repairDto.getEmName() + "】" : "【" + repairDto.getEmName() + "】（其他设备）";

        for (Long userId:userIdList){
            //待办
            commonService.insertMessageBacklog(
                    userId,
                    "新增维修单待审核，请处理",
                    content+ "新增一个维修单，地点在【" + repairDto.getEmLocation()  + "】，请审核维修申请信息。",
                    2, 1, repairWorkOrder.getRepId(), repairWorkOrder.getWorkOrderCode()
            );
            //通知
            commonService.insertMessageInform(
                    userId,
                    "新增非常紧急的维修，请知悉",
                    "【"+repairDto.getEmName()+"】新增非常紧急维修单，您可在工作分配界面进行工单分配，请知悉。",
                    2, 1, repairWorkOrder.getRepId(), repairWorkOrder.getWorkOrderCode()
            );

        }
        Map<String,Object> restMap = new HashMap<>();
        restMap.put("repId",repairWorkOrder.getRepId());
        return DataResult.build9100(restMap);
    }

    /*
     * 根据ID查询报修单详情
     * */
    @Override
    public DataResult getRepairById(LoginInfo loginInfo, String repId) throws Exception {
        RepairWorkOrder repairWorkOrder = repairWorkOrderMapper.selectByPrimaryKey(Long.parseLong(repId));
        if (repairWorkOrder == null) {
            return DataResult.build9100();
        }
        Map<String, Object> map = new HashMap<>();
        map.put("repId", repairWorkOrder.getRepId());
        map.put("workOrderCode", repairWorkOrder.getWorkOrderCode());
        map.put("repFaultType", repairWorkOrder.getRepFaultType());
        map.put("urgencyLevel", repairWorkOrder.getUrgencyLevel());
        map.put("repEmState", repairWorkOrder.getRepEmState());
        map.put("emStateDesc", repairWorkOrder.getEmStateDesc());
        map.put("repDesc", repairWorkOrder.getRepDesc());
        map.put("repState", repairWorkOrder.getRepState());
        map.put("repEmployeeName", commonService.getEmployeeNameById(repairWorkOrder.getEmployeeId()));
        map.put("repStartTime", DateUtil.format(repairWorkOrder.getRepStartTime(), "yyyy-MM-dd HH:mm:ss"));
        map.put("announceMap", null);
        map.put("maintenanceMap", null);
        map.put("maintenanceCompleteMap", null);
        map.put("sparePartMap", null);
        map.put("acceptMap", null);
        //获取设备信息
        EquipmentInfo equipmentInfo = equipmentInfoMapper.selectByPrimaryKey(repairWorkOrder.getEmId());
        if (equipmentInfo != null) {
            Map<Integer, String> typeEmGradeMap = commonService.getDictMap("TYPE_EM_GRADE");
            map.put("emName", equipmentInfo.getEmName());
            map.put("emCode", equipmentInfo.getEmCode());
            map.put("emGrade", typeEmGradeMap.get(equipmentInfo.getEmGrade()));
            map.put("emEmployeeName", "");
            map.put("emNumber", "");
            map.put("emLocation", equipmentInfo.getEmLocation());
        } else {
            map.put("emName", "");
            map.put("emSystem", "");
            map.put("emCode", "");
            map.put("emGrade", "");
            map.put("emGroup", "");
            map.put("emEmployeeName", "");
            map.put("emNumber", "");
            map.put("emLocation", "");
        }
        //上传文件
        getRepairFileList(map, repairWorkOrder.getRepId());

        int repState = repairWorkOrder.getRepState();
        if (repState == EnumRepState.PENDING_RECEIVE.getRepState() || repState == EnumRepState.PENDING_REFUSE.getRepState() || repState == EnumRepState.PENDING_TRANSFER.getRepState()) {
            //待领取,有审核数据
            addAnnounce(map, repairWorkOrder);
        } else if (repState == EnumRepState.ALLOCATED.getRepState() || repState == EnumRepState.UNDE_REPAIR.getRepState() || repState == EnumRepState.SUSPEND_REPAIR.getRepState()) {
            //已分配和维修中
            addAllocated(loginInfo, map, repairWorkOrder);
        } else if (repState == EnumRepState.ACCEPTED_NO.getRepState() || repState == EnumRepState.ACCEPTED_YES.getRepState()) {
            //待验收
            addAccepted(loginInfo, map, repairWorkOrder);
        } else if (repState == EnumRepState.MAINTENANCE_YES.getRepState()) {
            //验收通过
            RepairMaintenance repairMaintenance = addAccepted(loginInfo, map, repairWorkOrder);
            addAccept(map, repairMaintenance);
        }
        return DataResult.build9100(map);
    }

    /*
     * 根据ID查询报修单基本信息
     * */
    @Override
    public DataResult getBasicRepairById(LoginInfo loginInfo, String repId) throws Exception {
        Map<String, Object> map = new HashMap<>();
        RepairWorkOrder repairWorkOrder = repairWorkOrderMapper.selectByPrimaryKey(Long.parseLong(repId));
        if (repairWorkOrder == null) {
            return DataResult.build9100(map);
        }
        //故障类别
        Map<Integer, String> faultMap = commonService.getDictMap("TYPE_REP_FAULT");
        //紧急程度
        Map<Integer, String> urgencyMap = commonService.getDictMap("TYPE_URGENCY_LEVEL");
        //设备状态
        Map<Integer, String> emStateMap = commonService.getDictMap("TYPE_EM_STATE");

        //设备类型
        Map<Integer, String> emTypeMap = commonService.getDictMap("DEVICE_CLASSIFY");

        /*根据repairWorkOrder的mainten_employee_users_id查询到员工列表数据*/
        List<SystemEmployee> employeeList = systemEmployeeMapper.roleList();
        List<SystemEmployee> filteredEmployees = null;
        if (repairWorkOrder.getMaintenEmployeeUsersId() != null && !repairWorkOrder.getMaintenEmployeeUsersId().isEmpty()) {
            String[] maintenEmployeeUserIds = repairWorkOrder.getMaintenEmployeeUsersId().split(",");
            // 将字符串数组转换为Set，以便进行快速查找
            Set<Long> maintenEmployeeUserIdSet = Arrays.stream(maintenEmployeeUserIds)
                    .map(String::trim) // 去除前后空格
                    .filter(id -> id != null && !id.isEmpty() && !"null".equalsIgnoreCase(id)) // 过滤掉空字符串和 "null"
                    .map(Long::parseLong) // 将有效字符串转换为 Long
                    .collect(Collectors.toSet());
            // 使用Stream API过滤employeeList
            filteredEmployees = employeeList.stream()
                    .filter(employee -> maintenEmployeeUserIdSet.contains(employee.getId()))
                    .collect(Collectors.toList());
        }

        SystemEmployee se = systemEmployeeMapper.selectByPrimaryKey(repairWorkOrder.getEmployeeId());
        SystemUserExample suExample = new SystemUserExample();
        suExample.createCriteria().andEmployeeIdEqualTo(se.getId());
        List<SystemUser> suList = systemUserMapper.selectByExample(suExample);
        if (suList.size() != 0) {
            map.put("username", suList.get(0).getUsername());
            if (suList.get(0).getRoleId().equals(0L)) {
                map.put("roleName", "");
            } else {
                map.put("roleName", systemRoleMapper.selectByPrimaryKey(suList.get(0).getRoleId()).getRoleName());
            }
        } else {
            map.put("username", "");
            map.put("roleName", "");
        }
        map.put("positionName", commonService.getDictMap("TYPE_EMPLOYEE_POSITION").getOrDefault(se.getPosition(), ""));


        map.put("repId", repairWorkOrder.getRepId());
        map.put("workOrderCode", repairWorkOrder.getWorkOrderCode());
        map.put("repFaultType", repairWorkOrder.getRepFaultType());
        map.put("urgencyLevel", repairWorkOrder.getUrgencyLevel());
        map.put("repEmState", repairWorkOrder.getRepEmState());
        map.put("urgencyLevelName", urgencyMap.getOrDefault(repairWorkOrder.getUrgencyLevel(), ""));
        map.put("repFaultTypeName", faultMap.getOrDefault(repairWorkOrder.getRepFaultType(), ""));
        map.put("repEmStateName", emStateMap.getOrDefault(repairWorkOrder.getRepEmState(), ""));
        map.put("emStateDesc", repairWorkOrder.getEmStateDesc());
        map.put("repDesc", repairWorkOrder.getRepDesc());
        map.put("repState", repairWorkOrder.getRepState());
        map.put("repEmployeeName", commonService.getEmployeeNameById(repairWorkOrder.getEmployeeId()));
        SystemEmployee systemEmployee = SystemData.employeeMap.get(repairWorkOrder.getEmployeeId());
        if (systemEmployee != null) {
            map.put("repEmployeeNum", systemEmployee.getPhoneNumber());
        } else {
            map.put("repEmployeeNum", "");
        }
        map.put("repStartTime", DateUtil.format(repairWorkOrder.getRepStartTime(), "yyyy-MM-dd HH:mm:ss"));
        map.put("emId", repairWorkOrder.getEmId());
        //获取设备信息
        EquipmentInfo equipmentInfo = null;
        Integer eqType = 1;
        if (repairWorkOrder.getEmId() != 0) {
            equipmentInfo = equipmentInfoMapper.selectByPrimaryKey(repairWorkOrder.getEmId());

        }
        if (equipmentInfo != null) {
            EquipmentTree et = equipmentTreeMapper.selectByPrimaryKey(equipmentInfo.getEmTree());
            long emTreeSubsystemId;
            long emTreeGroupId = 0L;
            if (et.getType() == 2) { // 在子系统下
                emTreeSubsystemId = et.getId();
            } else {
                emTreeSubsystemId = et.getBaseId();
                emTreeGroupId = et.getId();
            }
            EquipmentTreeExample etExample = new EquipmentTreeExample();
            etExample.createCriteria().andIsDeleteEqualTo(0);
            List<EquipmentTree> etList = equipmentTreeMapper.selectByExample(etExample);
            List<String> nodeStr = equipmentTreeService.reverseSelectNode(etList, equipmentInfo.getEmTree());

            eqType = equipmentInfo.getDeviceClassify() == null ? 1 : tryParseInt(equipmentInfo.getDeviceClassify(),1);
            Map<Integer, String> typeEmGradeMap = commonService.getDictMap("TYPE_EM_GRADE");
            map.put("emName", equipmentInfo.getEmName());
            map.put("emCode", equipmentInfo.getEmCode());
            map.put("emGrade", typeEmGradeMap.get(equipmentInfo.getEmGrade()));
            map.put("emEmployeeName", "");
            map.put("emNumber", "");
            map.put("emLocation", equipmentInfo.getEmLocation());
            map.put("emSpecification", equipmentInfo.getEmSpecification());
            map.put("area",String.join("/", nodeStr));
            map.put("emTreeSubsystemId", emTreeSubsystemId);
            map.put("emTreeGroupId", emTreeGroupId);
            map.put("deviceClassify", eqType);
            map.put("deviceClassifyName", emTypeMap.get(eqType));

        } else {
            map.put("emName", repairWorkOrder.getEmName());
            map.put("emCode", repairWorkOrder.getEmCode());
            map.put("emGrade", "");
            map.put("emEmployeeName", "");
            map.put("emNumber", "");
            map.put("emLocation", repairWorkOrder.getEmLocation());
            map.put("emSpecification", repairWorkOrder.getEmSpecification());
            map.put("deviceClassify", eqType);
            map.put("deviceClassifyName", emTypeMap.get(eqType));
        }
        //上传文件
        getRepairFileList(map, repairWorkOrder.getRepId());

        //判定是否有按钮权限
        int repStateInt = repairWorkOrder.getRepState();
        boolean isFlag = false;
        RepairMaintenanceExample repMainExample = new RepairMaintenanceExample();
        RepairMaintenanceExample.Criteria repMainCriteria = repMainExample.createCriteria();
        repMainCriteria.andRepIdEqualTo(Long.parseLong(repId));
        repMainCriteria.andMtcStateEqualTo(repStateInt);
        repMainExample.setOrderByClause("create_time desc limit 1");
        List<RepairMaintenance> repairMaintenanceList = repairMaintenanceMapper.selectByExample(repMainExample);
        Long maintenanceId = null;
        if (CollUtil.isNotEmpty(repairMaintenanceList)) {
            RepairMaintenance repairMaintenance = repairMaintenanceList.get(0);
            maintenanceId = repairMaintenance.getId();
            if (repStateInt == EnumRepState.ALLOCATED.getRepState()
                    || repStateInt == EnumRepState.UNDE_REPAIR.getRepState()
                    || repStateInt == EnumRepState.SUSPEND_REPAIR.getRepState()) {
                //已分配和维修中,有维修按钮权限
                if (loginInfo.getLoginEmployeeId().equals(repairMaintenance.getEmployeeId())) {
                    isFlag = true;
                }
            }
            if (repStateInt == EnumRepState.ACCEPTED_YES.getRepState()) {
                //验收按钮权限
                if (loginInfo.getLoginEmployeeId().equals(repairMaintenance.getAcceptEmployeeId())) {
                    isFlag = true;
                }
            }
        }
        map.put("flag", isFlag);
        map.put("maintenanceId", maintenanceId);
        map.put("selectedItems",filteredEmployees);
        map.put("maintenanceCategoriesCode", repairWorkOrder.getMaintenanceCategories());
        return DataResult.build9100(map);
    }

    private Integer tryParseInt(String s,Integer defVal){
        try{
            return Integer.parseInt(s);
        }catch (Exception e){
            return defVal;
        }
    }

    @Override
    public DataResult getBasicRepairUpdateById(LoginInfo loginInfo, String repId, String maintenEmployeeUsersId) throws Exception {
        int rows = repairWorkOrderMapper.updateById(Long.valueOf(repId), maintenEmployeeUsersId);
        return DataResult.build9100(rows);
    }

    /*
     * 根据ID查询报修单审核信息
     * */
    @Override
    public DataResult getAnnounceRepairById(LoginInfo loginInfo, String repId, String repState) throws Exception {
        long repIdLong = Long.parseLong(repId);

        RepairWorkOrder repairWorkOrder = repairWorkOrderMapper.selectByPrimaryKey(repIdLong);
        if (repairWorkOrder == null) {
            return DataResult.build9100(new HashMap<>());
        }
        int repStateInt = repairWorkOrder.getRepState();
        //待审核没有信息
        if (repStateInt == EnumRepState.PENDING_ANNOUNCE.getRepState()) {
            return DataResult.build9100(new HashMap<>());
        }
        Map<String, Object> announceMap = getAnnounceMap(repIdLong);

        if (repairWorkOrder.getEstimatedWorkHour() != null) {
            announceMap.put("estimatedWorkHour", repairWorkOrder.getEstimatedWorkHour());
        } else {
            announceMap.put("estimatedWorkHour", "");
        }

        if (repStateInt == EnumRepState.INVALID.getRepState() || repStateInt == EnumRepState.PENDING_RECEIVE.getRepState()
                || repStateInt == EnumRepState.PENDING_REFUSE.getRepState() || repStateInt == EnumRepState.PENDING_TRANSFER.getRepState()) {
            announceMap.put("disEmployeeName", "");
            announceMap.put("disTime", "");
            return DataResult.build9100(announceMap);
        }

        RepairMaintenanceExample repMainExample = new RepairMaintenanceExample();
        RepairMaintenanceExample.Criteria repMainCriteria = repMainExample.createCriteria();
        repMainCriteria.andRepIdEqualTo(repIdLong);
        repMainCriteria.andMtcStateEqualTo(repStateInt);
        repMainExample.setOrderByClause("create_time desc limit 1");
        List<RepairMaintenance> repairMaintenanceList = repairMaintenanceMapper.selectByExample(repMainExample);
        if (CollUtil.isEmpty(repairMaintenanceList)) {
            announceMap.put("disEmployeeName", "");
            announceMap.put("disTime", "");
            return DataResult.build9100(announceMap);
        }
        //派生信息获取开始
        RepairMaintenance repairMaintenance = repairMaintenanceList.get(0);
        announceMap.put("disTime", DateUtil.format(repairMaintenance.getDisTime(), "yyyy-MM-dd HH:mm:ss"));
        //维修人员
        if (repairMaintenance.getDisType() == 1) {
            announceMap.put("disEmployeeName", "系统自动分配");
        } else if (repairMaintenance.getDisType() == 2) {
            String disEmployeeName = commonService.getEmployeeNameById(repairMaintenance.getDisEmployeeId());
            if (StrUtil.isNotBlank(disEmployeeName)) {
                announceMap.put("disEmployeeName", disEmployeeName + "自己领取");
            } else {
                announceMap.put("disEmployeeName", "");
            }
        } else if (repairMaintenance.getDisType() == 3) {
            announceMap.put("disEmployeeName", commonService.getEmployeeNameById(repairMaintenance.getDisEmployeeId()));
        } else {
            announceMap.put("disEmployeeName", "");
        }
        return DataResult.build9100(announceMap);
    }

    /*
     * 根据ID查询报修单维修信息
     * */
    @Override
    public DataResult getMaintenanceRepairById(LoginInfo loginInfo, String repId, String repState) throws Exception {
        Map<String, Object> maintenanceMap = new HashMap<>();
        long repIdLong = Long.parseLong(repId);
        RepairWorkOrder repairWorkOrder = repairWorkOrderMapper.selectByPrimaryKey(repIdLong);
        if (repairWorkOrder == null) {
            return DataResult.build9100(new HashMap<>());
        }
        int repStateInt = repairWorkOrder.getRepState();
        if (repStateInt == EnumRepState.INVALID.getRepState() || repStateInt == EnumRepState.PENDING_ANNOUNCE.getRepState()
                || repStateInt == EnumRepState.PENDING_RECEIVE.getRepState() || repStateInt == EnumRepState.PENDING_REFUSE.getRepState()
                || repStateInt == EnumRepState.PENDING_TRANSFER.getRepState()) {
            return DataResult.build9100(maintenanceMap);
        }

        RepairMaintenanceExample repMainExample = new RepairMaintenanceExample();
        RepairMaintenanceExample.Criteria repMainCriteria = repMainExample.createCriteria();
        repMainCriteria.andRepIdEqualTo(repIdLong);
        repMainCriteria.andMtcStateEqualTo(repStateInt);
        repMainExample.setOrderByClause("create_time desc limit 1");
        List<RepairMaintenance> repairMaintenanceList = repairMaintenanceMapper.selectByExample(repMainExample);
        if (CollUtil.isEmpty(repairMaintenanceList)) {
            return DataResult.build9100(maintenanceMap);
        }
        RepairMaintenance repairMaintenance = repairMaintenanceList.get(0);

        //维修信息获取开始
        maintenanceMap.put("employeeName", commonService.getEmployeeNameById(repairMaintenance.getEmployeeId()));
        maintenanceMap.put("id", repairMaintenance.getId());
        maintenanceMap.put("isReuse", repairMaintenance.getIsReuse());
        if (repStateInt != EnumRepState.ALLOCATED.getRepState()) {
            maintenanceMap.put("mtcStartTime", DateUtil.format(repairMaintenance.getMtcStartTime(), "yyyy-MM-dd HH:mm:ss"));
        } else {
            maintenanceMap.put("mtcStartTime", "");
        }

        //故障类别
        Map<Integer, String> faultTypeMap = commonService.getDictMap("TYPE_REP_MAINTENANCE");
        //故障原因
        Map<Integer, String> reasonMap = commonService.getDictMap("TYPE_REP_REASON");
        //设备状态
        Map<Integer, String> emStateMap = commonService.getDictMap("TYPE_EM_STATE");

        maintenanceMap.put("mtcEmState", repairMaintenance.getMtcEmState());
        maintenanceMap.put("mtcFaultReason", repairMaintenance.getMtcFaultReason());
        maintenanceMap.put("mtcFaultType", repairMaintenance.getMtcFaultType());

        maintenanceMap.put("mtcEmStateName", emStateMap.getOrDefault(repairMaintenance.getMtcEmState(), ""));
        maintenanceMap.put("mtcFaultReasonName", reasonMap.getOrDefault(repairMaintenance.getMtcFaultReason(), ""));
        maintenanceMap.put("mtcFaultTypeName", faultTypeMap.getOrDefault(repairMaintenance.getMtcFaultType(), ""));

        maintenanceMap.put("mtcStateDesc", repairMaintenance.getMtcStateDesc());
        maintenanceMap.put("mtcDesc", repairMaintenance.getMtcDesc());
        maintenanceMap.put("currentStatusAnalysis", repairMaintenance.getCurrentStatusAnalysis());
        getMaintenanceFileList(maintenanceMap, repairMaintenance.getId());

        if (repStateInt == EnumRepState.ALLOCATED.getRepState() || repStateInt == EnumRepState.UNDE_REPAIR.getRepState() || repStateInt == EnumRepState.SUSPEND_REPAIR.getRepState()) {
            //已分配和维修中
            if (loginInfo.getLoginEmployeeId().equals(repairMaintenance.getEmployeeId())) {
                maintenanceMap.put("flag", true);
            } else {
                maintenanceMap.put("flag", false);
            }
            return DataResult.build9100(maintenanceMap);
        }
        maintenanceMap.put("mtcEndTime", DateUtil.format(repairMaintenance.getMtcEndTime(), "yyyy-MM-dd HH:mm:ss"));

        //计算后维修的时间
        int isReuse = repairMaintenance.getIsReuse();
        long countMtcSecond = 0;
        long suspendSecond = 0;
        if (isReuse == 1) {
            countMtcSecond = repairMaintenance.getMtcSecond();
            suspendSecond = repairMaintenance.getSuspendSecond();
        } else if (isReuse == 2 && StrUtil.isNotBlank(repairMaintenance.getAssMtcId())) {
            //多次维修
            RepairMaintenanceExample isReuseMainExample = new RepairMaintenanceExample();
            RepairMaintenanceExample.Criteria isReuseMainCriteria = isReuseMainExample.createCriteria();
            String assMtcId = repairMaintenance.getAssMtcId();
            if (assMtcId.contains(",")) {
                String[] split = assMtcId.split(",");
                List<Long> idList = new ArrayList<>();
                for (String sp : split) {
                    if (StrUtil.isNotBlank(sp)) {
                        idList.add(Long.parseLong(sp));
                    }
                }
                isReuseMainCriteria.andIdIn(idList);
                List<RepairMaintenance> isReuseMaintenanceList = repairMaintenanceMapper.selectByExample(isReuseMainExample);
                countMtcSecond = repairMaintenance.getMtcSecond();
                suspendSecond = repairMaintenance.getSuspendSecond();
                for (RepairMaintenance forRepairMaintenance : isReuseMaintenanceList) {
                    countMtcSecond += forRepairMaintenance.getMtcSecond();
                    suspendSecond += forRepairMaintenance.getSuspendSecond();
                }
            } else {
                RepairMaintenance isReuseMaintenance = repairMaintenanceMapper.selectByPrimaryKey(Long.parseLong(assMtcId));
                countMtcSecond = repairMaintenance.getMtcSecond() + isReuseMaintenance.getMtcSecond();
                suspendSecond = repairMaintenance.getSuspendSecond() + isReuseMaintenance.getSuspendSecond();
            }
        }

        String countMtcSecondStr = getTimeStr(countMtcSecond);
        String suspendSecondStr = getTimeStr(suspendSecond);

        if (countMtcSecond <= 0) {
            maintenanceMap.put("mtcSecond", "");
        } else {
            maintenanceMap.put("mtcSecond", countMtcSecondStr);
        }

        if (suspendSecond <= 0) {
            maintenanceMap.put("suspendSecond", "无");
        } else {
            maintenanceMap.put("suspendSecond", suspendSecondStr);
        }

        return DataResult.build9100(maintenanceMap);
    }

    /*
     * 查询验收信息
     * */
    @Override
    public DataResult getAcceptById(LoginInfo loginInfo, String repId, String repState) throws Exception {
        Map<String, Object> acceptMap = new HashMap<>();
        int repStateInt = Integer.parseInt(repState);
        long repIdLong = Long.parseLong(repId);
        if (repStateInt == EnumRepState.INVALID.getRepState() || repStateInt == EnumRepState.PENDING_ANNOUNCE.getRepState()
                || repStateInt == EnumRepState.PENDING_RECEIVE.getRepState() || repStateInt == EnumRepState.PENDING_REFUSE.getRepState()
                || repStateInt == EnumRepState.PENDING_TRANSFER.getRepState()) {
            return DataResult.build9100(acceptMap);
        }

        if (repStateInt == EnumRepState.ALLOCATED.getRepState() || repStateInt == EnumRepState.UNDE_REPAIR.getRepState()
                || repStateInt == EnumRepState.SUSPEND_REPAIR.getRepState() || repStateInt == EnumRepState.ACCEPTED_NO.getRepState()) {
            return DataResult.build9100(acceptMap);
        }

        //派生信息获取开始
        RepairMaintenanceExample repMainExample = new RepairMaintenanceExample();
        RepairMaintenanceExample.Criteria repMainCriteria = repMainExample.createCriteria();
        repMainCriteria.andRepIdEqualTo(repIdLong);
        repMainCriteria.andMtcStateEqualTo(repStateInt);
        repMainExample.setOrderByClause("create_time desc limit 1");
        List<RepairMaintenance> repairMaintenanceList = repairMaintenanceMapper.selectByExample(repMainExample);
        if (CollUtil.isEmpty(repairMaintenanceList)) {
            return DataResult.build9100(acceptMap);
        }

        if (repStateInt == EnumRepState.ACCEPTED_YES.getRepState()) {
            if (repairMaintenanceList.get(0).getAcceptEmployeeId() != null) {
                acceptMap.put("employeeName", commonService.getEmployeeNameById(repairMaintenanceList.get(0).getAcceptEmployeeId()));
                return DataResult.build9100(acceptMap);
            }
        }

        BusinessAcceptExample accExample = new BusinessAcceptExample();
        BusinessAcceptExample.Criteria accCriteria = accExample.createCriteria();
        accCriteria.andSourceIdEqualTo(repairMaintenanceList.get(0).getId());
        accCriteria.andBusTypeEqualTo(EnumAcceptBusinessType.MAINTENANCE.getBusType());
        accExample.setOrderByClause("create_time desc limit 1");
        List<BusinessAccept> businessAccepts = businessAcceptMapper.selectByExample(accExample);
        if (CollUtil.isNotEmpty(businessAccepts)) {
            BusinessAccept businessAccept = businessAccepts.get(0);
            if (1 == businessAccept.getAcceptState()) {
                acceptMap.put("acceptStateName", "验收通过");
            } else if (2 == businessAccept.getAcceptState()) {
                acceptMap.put("acceptStateName", "验收驳回");
            }
            acceptMap.put("employeeName", commonService.getEmployeeNameById(businessAccept.getEmployeeId()));
            acceptMap.put("acceptExplain", businessAccept.getAcceptExplain());
            acceptMap.put("acceptScore", businessAccept.getAcceptScore());
            acceptMap.put("acceptState", businessAccept.getAcceptState());
            acceptMap.put("acceptTime", DateUtil.format(businessAccept.getAcceptTime(), "yyyy-MM-dd HH:mm:ss"));
        }
        return DataResult.build9100(acceptMap);
    }

    /*
     * 领取工单
     * receiveType = 1 自己领取
     * receiveType = 2 领导派单
     * */
    @Override
    public DataResult receiveRepair(LoginInfo loginInfo, String repId, String receiveType, String employeeId) throws Exception {
        RepairWorkOrder getRepairWorkOrder = repairWorkOrderMapper.selectByPrimaryKey(Long.parseLong(repId));
        if (getRepairWorkOrder == null) {
            return DataResult.build9250("获取维修工单信息失败！");
        }
        if (!getRepairWorkOrder.getRepState().equals(EnumRepState.PENDING_RECEIVE.getRepState())
                && !getRepairWorkOrder.getRepState().equals(EnumRepState.PENDING_REFUSE.getRepState())
                && !getRepairWorkOrder.getRepState().equals(EnumRepState.PENDING_TRANSFER.getRepState())) {
            return DataResult.build9250("只有待领取状态的工单才能领取工单！！");
        }
        //修改维修单状态
        RepairMaintenance repairMaintenance = new RepairMaintenance();
        repairMaintenance.setRepId(Long.parseLong(repId));
        repairMaintenance.setDisTime(new Date());
        repairMaintenance.setMtcState(EnumRepState.ALLOCATED.getRepState());
        repairMaintenance.setCreateTime(new Date());
        //修改维修工单状态:1,自己领取:2,领导派单
        String flowDesc = "";
        if ("1".equals(receiveType)) {
            if (getRepairWorkOrder.getRepState().equals(EnumRepState.PENDING_REFUSE.getRepState())
                    || getRepairWorkOrder.getRepState().equals(EnumRepState.PENDING_TRANSFER.getRepState())) {
                return DataResult.build9250("拒单和转交的工单只能领导分配，不能自己领取！！");
            }
            //分配类型:2自己抢单；3管理人员分配
            repairMaintenance.setDisType(2);
            //分配人
            repairMaintenance.setDisEmployeeId(loginInfo.getLoginEmployeeId());
            //维修人
            repairMaintenance.setEmployeeId(loginInfo.getLoginEmployeeId());
            flowDesc = "领取工单";
        } else if ("2".equals(receiveType)) {
            if (StrUtil.isNotBlank(employeeId)) {
                repairMaintenance.setDisType(3);
                repairMaintenance.setDisEmployeeId(loginInfo.getLoginEmployeeId());
                repairMaintenance.setEmployeeId(Long.parseLong(employeeId));
                flowDesc = "指派工单";
            } else {
                return DataResult.build9250("派单请选择维修人员!!!");
            }
        }
        //修改工单状态
        RepairWorkOrder repairWorkOrder = new RepairWorkOrder();
        repairWorkOrder.setRepId(Long.parseLong(repId));
        repairWorkOrder.setMaintenEmployeeId(repairMaintenance.getEmployeeId());
        repairWorkOrder.setRepState(EnumRepState.ALLOCATED.getRepState());
        repairWorkOrderMapper.updateByPrimaryKeySelective(repairWorkOrder);
        repairMaintenanceMapper.insertSelective(repairMaintenance);
        //记录流水
        insertDisFlow(repairWorkOrder.getRepId(), repairMaintenance.getEmployeeId(), 3, repairMaintenance.getId(), EnumRepState.ALLOCATED.getRepState(), flowDesc, loginInfo.getLoginEmployeeId());
        //待办
        commonService.insertMessageBacklog(
                repairMaintenance.getEmployeeId(),
                "【"+getRepairWorkOrder.getWorkOrderCode()+"】维修单已分配到您，请处理",
                "【" + getRepairWorkOrder.getWorkOrderCode() + "】已分配到您，维修设备：【" + getRepairWorkOrder.getEmCode() + "】-【" + getRepairWorkOrder.getEmName() + "】，地点在【" + getRepairWorkOrder.getEmLocation()  + "】，工单在【30分钟】后自动进入处理中，请尽快到场处理。",
                2, 2, repairWorkOrder.getRepId(), getRepairWorkOrder.getWorkOrderCode()
        );

        return DataResult.build9100();
    }

    /*
     * 手动点击维修中
     * */
    @Override
    public DataResult undeRepair(LoginInfo loginInfo, String id) throws Exception {
        RepairMaintenance repairMaintenance = repairMaintenanceMapper.selectByPrimaryKey(Long.parseLong(id));
        if (repairMaintenance == null) {
            return DataResult.build9250("获取维修人员信息失败！");
        }

        if (!repairMaintenance.getMtcState().equals(EnumRepState.ALLOCATED.getRepState())) {
            return DataResult.build9250("已分配的工单才能开始维修中!");
        }

        if (!repairMaintenance.getEmployeeId().equals(loginInfo.getLoginEmployeeId())) {
            String errName = commonService.getEmployeeNameById(repairMaintenance.getEmployeeId());
            return DataResult.build9250("人员" + errName + "才能操作");
        }

        RepairMaintenance updateRepairMaintenance = new RepairMaintenance();
        updateRepairMaintenance.setId(repairMaintenance.getId());
        updateRepairMaintenance.setMtcState(EnumRepState.UNDE_REPAIR.getRepState());
        //processType;1,系统计时自动，2，手动点击
        updateRepairMaintenance.setProcessType(2);
        updateRepairMaintenance.setMtcStartTime(new Date());
        repairMaintenanceMapper.updateByPrimaryKeySelective(updateRepairMaintenance);
        RepairWorkOrder updateRepairWorkOrder = new RepairWorkOrder();
        updateRepairWorkOrder.setRepId(repairMaintenance.getRepId());
        updateRepairWorkOrder.setRepState(EnumRepState.UNDE_REPAIR.getRepState());
        repairWorkOrderMapper.updateByPrimaryKeySelective(updateRepairWorkOrder);
        //记录流水
        insertFlow(repairMaintenance.getRepId(), repairMaintenance.getEmployeeId(), 3, repairMaintenance.getId(), EnumRepState.UNDE_REPAIR.getRepState(), "维修中");
        return DataResult.build9100();
    }

    /*
     * 点击拒单
     * */
    @Override
    public DataResult refuseRepair(LoginInfo loginInfo, String id) throws Exception {
        RepairMaintenance repairMaintenance = repairMaintenanceMapper.selectByPrimaryKey(Long.parseLong(id));
        if (repairMaintenance == null) {
            return DataResult.build9250("获取维修人员信息失败！");
        }

        RepairWorkOrder getRepairWorkOrder = repairWorkOrderMapper.selectByPrimaryKey(repairMaintenance.getRepId());

        if (!repairMaintenance.getEmployeeId().equals(loginInfo.getLoginEmployeeId())) {
            String errName = commonService.getEmployeeNameById(repairMaintenance.getEmployeeId());
            return DataResult.build9250("人员" + errName + "才能操作");
        }

        if (!repairMaintenance.getMtcState().equals(EnumRepState.ALLOCATED.getRepState())) {
            return DataResult.build9250("已分配的工单才能拒单!");
        }

        if (repairMaintenance.getDisType() == 2) {
            return DataResult.build9250("自己领取的工单不能拒单!");
        }
        RepairMaintenance updateRepairMaintenance = new RepairMaintenance();
        updateRepairMaintenance.setId(repairMaintenance.getId());
        updateRepairMaintenance.setMtcState(EnumRepState.INVALID.getRepState());
        //processType;3,拒单
        updateRepairMaintenance.setProcessType(3);
        repairMaintenanceMapper.updateByPrimaryKeySelective(updateRepairMaintenance);
        RepairWorkOrder updateRepairWorkOrder = new RepairWorkOrder();
        updateRepairWorkOrder.setRepId(repairMaintenance.getRepId());
        updateRepairWorkOrder.setRepState(EnumRepState.PENDING_REFUSE.getRepState());
        repairWorkOrderMapper.updateByPrimaryKeySelective(updateRepairWorkOrder);
        //记录流水
        insertFlow(repairMaintenance.getRepId(), repairMaintenance.getEmployeeId(), 3, repairMaintenance.getId(), EnumRepState.PENDING_REFUSE.getRepState(), "拒单");

        List<Long> userIdList = commonService.selectManagerUserIdList(2);
        for (Long userId:userIdList){
            //待办
            commonService.insertMessageBacklog(
                    userId,
                    "【"+getRepairWorkOrder.getWorkOrderCode()+"】已退回，请重新分配",
                    "【"+getRepairWorkOrder.getWorkOrderCode()+"】已退回，退回原因：【拒单原因】，请重新分配工作。",
                    2, 3, getRepairWorkOrder.getRepId(), getRepairWorkOrder.getWorkOrderCode()
            );
        }

        return DataResult.build9100();
    }

    /*
     * 暂停和开始维修
     * type;1,暂停；2开始维修
     * */
    @Override
    public DataResult suspendRepair(LoginInfo loginInfo, String id, String type) throws Exception {
        RepairMaintenance repairMaintenance = repairMaintenanceMapper.selectByPrimaryKey(Long.parseLong(id));
        if (repairMaintenance == null) {
            return DataResult.build9250("获取维修人员信息失败！");
        }
        if (!loginInfo.getLoginEmployeeId().equals(repairMaintenance.getEmployeeId())) {
            String errName = commonService.getEmployeeNameById(repairMaintenance.getEmployeeId());
            return DataResult.build9250("人员" + errName + "才能操作");
        }
        int mtcState = repairMaintenance.getMtcState();
        //修改维修表状态
        RepairMaintenance updateRepairMaintenance = new RepairMaintenance();
        updateRepairMaintenance.setId(repairMaintenance.getId());
        //工单表状态同步
        RepairWorkOrder updateRepairWorkOrder = new RepairWorkOrder();
        updateRepairWorkOrder.setRepId(repairMaintenance.getRepId());
        int flowState = 0;
        String flowDesc = "";
        if ("2".equals(type)) {
            if (mtcState != EnumRepState.SUSPEND_REPAIR.getRepState()) {
                return DataResult.build9250("暂停中的维修单才能恢复维修中!");
            }
            updateRepairWorkOrder.setRepState(EnumRepState.UNDE_REPAIR.getRepState());
            updateRepairMaintenance.setMtcState(EnumRepState.UNDE_REPAIR.getRepState());
            flowState = EnumRepState.UNDE_REPAIR.getRepState();
            flowDesc = "开始维修";
            //暂停时间计算
            RepairMaintenanceSuspendExample msExample = new RepairMaintenanceSuspendExample();
            RepairMaintenanceSuspendExample.Criteria msCriteria = msExample.createCriteria();
            msCriteria.andMaintenanceIdEqualTo(repairMaintenance.getId());
            msCriteria.andStateEqualTo(1);
            msExample.setOrderByClause("start_time desc limit 1");
            List<RepairMaintenanceSuspend> repairMaintenanceSuspends = repairMaintenanceSuspendMapper.selectByExample(msExample);
            if (CollUtil.isNotEmpty(repairMaintenanceSuspends)) {
                RepairMaintenanceSuspend getRepairMaintenanceSuspend = repairMaintenanceSuspends.get(0);
                RepairMaintenanceSuspend repairMaintenanceSuspend = new RepairMaintenanceSuspend();
                repairMaintenanceSuspend.setId(getRepairMaintenanceSuspend.getId());
                repairMaintenanceSuspend.setState(2);
                repairMaintenanceSuspend.setEndTime(new Date());
                long between = DateUtil.between(getRepairMaintenanceSuspend.getStartTime(), repairMaintenanceSuspend.getEndTime(), DateUnit.SECOND);
                repairMaintenanceSuspend.setSuspendSecond(between);
                repairMaintenanceSuspendMapper.updateByPrimaryKeySelective(repairMaintenanceSuspend);
            }
        } else {
            if (mtcState != EnumRepState.UNDE_REPAIR.getRepState()) {
                return DataResult.build9250("维修中的工单才能暂停!");
            }
            flowState = EnumRepState.SUSPEND_REPAIR.getRepState();
            flowDesc = "暂停维修";
            RepairMaintenanceSuspend maintenanceSuspend = new RepairMaintenanceSuspend();
            maintenanceSuspend.setMaintenanceId(repairMaintenance.getId());
            maintenanceSuspend.setStartTime(new Date());
            maintenanceSuspend.setState(1);
            repairMaintenanceSuspendMapper.insertSelective(maintenanceSuspend);
            updateRepairWorkOrder.setRepState(EnumRepState.SUSPEND_REPAIR.getRepState());
            updateRepairMaintenance.setMtcState(EnumRepState.SUSPEND_REPAIR.getRepState());
        }
        repairMaintenanceMapper.updateByPrimaryKeySelective(updateRepairMaintenance);
        repairWorkOrderMapper.updateByPrimaryKeySelective(updateRepairWorkOrder);
        //记录流水
        insertFlow(repairMaintenance.getRepId(), repairMaintenance.getEmployeeId(), 3, repairMaintenance.getId(), flowState, flowDesc);
        return DataResult.build9100();
    }

    /*
     * 维修保存
     * */
    @Override
    public DataResult insertSuspendRepair(LoginInfo loginInfo, RepairMaintenanceInsDto repairMaintenanceDto) throws Exception {
        RepairMaintenance repairMaintenance = repairMaintenanceMapper.selectByPrimaryKey(Long.parseLong(repairMaintenanceDto.getId()));
        if (repairMaintenance == null) {
            return DataResult.build9250("获取维修人员信息失败！");
        }
        if (!loginInfo.getLoginEmployeeId().equals(repairMaintenance.getEmployeeId())) {
            String errName = commonService.getEmployeeNameById(repairMaintenance.getEmployeeId());
            return DataResult.build9250("人员" + errName + "才能操作");
        }
        if (!EnumRepState.UNDE_REPAIR.getRepState().equals(repairMaintenance.getMtcState())) {
            return DataResult.build9250("维修中的工单才能操作!");
        }
        //编辑数据
        RepairMaintenance updateRepairMaintenance = new RepairMaintenance();
        updateRepairMaintenance.setId(repairMaintenance.getId());

        if (StrUtil.isNotBlank(repairMaintenanceDto.getMtcEmState())) {
            updateRepairMaintenance.setMtcEmState(Integer.parseInt(repairMaintenanceDto.getMtcEmState()));
        }
        if (StrUtil.isNotBlank(repairMaintenanceDto.getMtcStateDesc())) {
            updateRepairMaintenance.setMtcStateDesc(repairMaintenanceDto.getMtcStateDesc());
        } else {
            updateRepairMaintenance.setMtcStateDesc("");
        }

        if (StrUtil.isNotBlank(repairMaintenanceDto.getMtcFaultType())) {
            updateRepairMaintenance.setMtcFaultType(Integer.parseInt(repairMaintenanceDto.getMtcFaultType()));
        }

        if (StrUtil.isNotBlank(repairMaintenanceDto.getMtcFaultReason())) {
            updateRepairMaintenance.setMtcFaultReason(Integer.parseInt(repairMaintenanceDto.getMtcFaultReason()));
        }

        if (StrUtil.isNotBlank(repairMaintenanceDto.getMtcDesc())) {
            updateRepairMaintenance.setMtcDesc(repairMaintenanceDto.getMtcDesc());
        } else {
            updateRepairMaintenance.setMtcDesc("");
        }
        if (StrUtil.isNotBlank(repairMaintenanceDto.getCurrentStatusAnalysis())) {
            updateRepairMaintenance.setCurrentStatusAnalysis(repairMaintenanceDto.getCurrentStatusAnalysis());
        } else {
            updateRepairMaintenance.setCurrentStatusAnalysis("");
        }
        repairMaintenanceMapper.updateByPrimaryKeySelective(updateRepairMaintenance);
        RepairMaintenanceDto dto = new RepairMaintenanceDto();
        dto.setFileNewAudioCode(repairMaintenanceDto.getFileNewAudioCode());
        dto.setFileNewPicCode(repairMaintenanceDto.getFileNewPicCode());
        dto.setFileNewVideoCode(repairMaintenanceDto.getFileNewVideoCode());
        dto.setFileOldAudioCode(repairMaintenanceDto.getFileOldAudioCode());
        dto.setFileOldPicCode(repairMaintenanceDto.getFileOldPicCode());
        dto.setFileOldVideoCode(repairMaintenanceDto.getFileOldVideoCode());
        //保存上传文件
        BusinessFileExample fileExample = new BusinessFileExample();
        BusinessFileExample.Criteria fileCriteria = fileExample.createCriteria();
        fileCriteria.andBusTablesIdEqualTo(repairMaintenance.getId());
        fileCriteria.andBusTypeEqualTo(EnumBusinessType.MAINTENANCE.getBusType());
        businessFileMapper.deleteByExample(fileExample);
        insertMaintenanceFile(repairMaintenance.getId(), loginInfo.getLoginEmployeeId(), dto);
        return DataResult.build9100();
    }

    /*
     * 工单转交
     * */
    @Override
    public DataResult transferRepair(LoginInfo loginInfo, String id) throws Exception {
        RepairMaintenance repairMaintenance = repairMaintenanceMapper.selectByPrimaryKey(Long.parseLong(id));
        if (repairMaintenance == null) {
            return DataResult.build9250("获取维修人员信息失败！");
        }
        if (!loginInfo.getLoginEmployeeId().equals(repairMaintenance.getEmployeeId())) {
            String errName = commonService.getEmployeeNameById(repairMaintenance.getEmployeeId());
            return DataResult.build9250("人员" + errName + "才能操作");
        }
        if (!EnumRepState.SUSPEND_REPAIR.getRepState().equals(repairMaintenance.getMtcState())) {
            return DataResult.build9250("暂停的工单才能转交!");
        }
        RepairMaintenance updateRepairMaintenance = new RepairMaintenance();
        updateRepairMaintenance.setId(repairMaintenance.getId());
        updateRepairMaintenance.setMtcState(EnumRepState.INVALID.getRepState());
        //processType;4,转交
        updateRepairMaintenance.setProcessType(4);
        repairMaintenanceMapper.updateByPrimaryKeySelective(updateRepairMaintenance);
        RepairWorkOrder updateRepairWorkOrder = new RepairWorkOrder();
        updateRepairWorkOrder.setRepId(repairMaintenance.getRepId());
        updateRepairWorkOrder.setRepState(EnumRepState.PENDING_TRANSFER.getRepState());
        repairWorkOrderMapper.updateByPrimaryKeySelective(updateRepairWorkOrder);
        //记录流水
        insertFlow(repairMaintenance.getRepId(), repairMaintenance.getEmployeeId(), 3, repairMaintenance.getId(), EnumRepState.PENDING_TRANSFER.getRepState(), "工单转交");
        return DataResult.build9100();
    }

    /*
     * 点击维修完成
     * */
    @Override
    public DataResult completeRepair(LoginInfo loginInfo, RepairMaintenanceDto repairMaintenanceDto) throws Exception {
        RepairMaintenance repairMaintenance = repairMaintenanceMapper.selectByPrimaryKey(Long.parseLong(repairMaintenanceDto.getId()));
        if (repairMaintenance == null) {
            return DataResult.build9250("获取维修人员信息失败！");
        }
        if (!loginInfo.getLoginEmployeeId().equals(repairMaintenance.getEmployeeId())) {
            String errName = commonService.getEmployeeNameById(repairMaintenance.getEmployeeId());
            return DataResult.build9250("人员" + errName + "才能操作");
        }
        if (!EnumRepState.UNDE_REPAIR.getRepState().equals(repairMaintenance.getMtcState())) {
            return DataResult.build9250("维修中的工单才能操作!");
        }
        //编辑数据
        RepairMaintenance updateRepairMaintenance = new RepairMaintenance();
        updateRepairMaintenance.setId(repairMaintenance.getId());
        updateRepairMaintenance.setMtcState(EnumRepState.ACCEPTED_NO.getRepState());
        if (StrUtil.isNotBlank(repairMaintenanceDto.getMtcStateDesc())) {
            updateRepairMaintenance.setMtcStateDesc(repairMaintenanceDto.getMtcStateDesc());
        } else {
            updateRepairMaintenance.setMtcStateDesc("");
        }
        if (StrUtil.isNotBlank(repairMaintenanceDto.getMtcEmState())) {
            updateRepairMaintenance.setMtcEmState(Integer.parseInt(repairMaintenanceDto.getMtcEmState()));
        }
        updateRepairMaintenance.setMtcFaultType(Integer.parseInt(repairMaintenanceDto.getMtcFaultType()));
        updateRepairMaintenance.setMtcFaultReason(Integer.parseInt(repairMaintenanceDto.getMtcFaultReason()));
        if (StrUtil.isNotBlank(repairMaintenanceDto.getMtcDesc())) {
            updateRepairMaintenance.setMtcDesc(repairMaintenanceDto.getMtcDesc());
        } else {
            updateRepairMaintenance.setMtcDesc("");
        }
        if (StrUtil.isNotBlank(repairMaintenanceDto.getCurrentStatusAnalysis())) {
            updateRepairMaintenance.setCurrentStatusAnalysis(repairMaintenanceDto.getCurrentStatusAnalysis());
        } else {
            updateRepairMaintenance.setMtcDesc("");
        }
        updateRepairMaintenance.setMtcEndTime(new Date());
        //计算维修时间
        long between = DateUtil.between(repairMaintenance.getMtcStartTime(), updateRepairMaintenance.getMtcEndTime(), DateUnit.SECOND);

        RepairMaintenanceSuspendExample supendExample = new RepairMaintenanceSuspendExample();
        RepairMaintenanceSuspendExample.Criteria supendCriteria = supendExample.createCriteria();
        supendCriteria.andMaintenanceIdEqualTo(repairMaintenance.getId());
        supendCriteria.andStateEqualTo(2);
        List<RepairMaintenanceSuspend> repairMaintenanceSuspends = repairMaintenanceSuspendMapper.selectByExample(supendExample);
        long suspendSecond = 0;
        for (RepairMaintenanceSuspend suspendInfo : repairMaintenanceSuspends) {
            if (suspendInfo.getSuspendSecond() != 0) {
                suspendSecond += suspendInfo.getSuspendSecond();
            }
        }

        long countMtcSecond = between - suspendSecond;
        if (countMtcSecond < 0) {
            countMtcSecond = 0;
        }
        updateRepairMaintenance.setMtcSecond(countMtcSecond);
        updateRepairMaintenance.setSuspendSecond(suspendSecond);
        repairMaintenanceMapper.updateByPrimaryKeySelective(updateRepairMaintenance);
        //保存上传文件
        BusinessFileExample fileExample = new BusinessFileExample();
        BusinessFileExample.Criteria fileCriteria = fileExample.createCriteria();
        fileCriteria.andBusTablesIdEqualTo(repairMaintenance.getId());
        fileCriteria.andBusTypeEqualTo(EnumBusinessType.MAINTENANCE.getBusType());
        businessFileMapper.deleteByExample(fileExample);
        insertMaintenanceFile(repairMaintenance.getId(), loginInfo.getLoginEmployeeId(), repairMaintenanceDto);
        RepairWorkOrder updateRepairWorkOrder = new RepairWorkOrder();
        updateRepairWorkOrder.setRepId(repairMaintenance.getRepId());
        updateRepairWorkOrder.setRepState(EnumRepState.ACCEPTED_NO.getRepState());
        updateRepairWorkOrder.setRepEndTime(new Date());
        repairWorkOrderMapper.updateByPrimaryKeySelective(updateRepairWorkOrder);
        RepairWorkOrder getRepairWorkOrder = repairWorkOrderMapper.selectByPrimaryKey(repairMaintenance.getRepId());

        //记录流水
        insertFlow(repairMaintenance.getRepId(), repairMaintenance.getEmployeeId(), 3, repairMaintenance.getId(), EnumRepState.ACCEPTED_NO.getRepState(), "维修提交验收");

        List<Long> userIdList = commonService.selectManagerUserIdList(2);
        for (Long userId:userIdList){
            //待办
            commonService.insertMessageBacklog(
                    userId,
                    "【"+getRepairWorkOrder.getWorkOrderCode()+"】已维修完工，请指定验收人员",
                    "【"+getRepairWorkOrder.getWorkOrderCode()+"】已维修完工，请指定验收人员进行现场验收。维修设备：【" + getRepairWorkOrder.getEmCode() + "】-【" + getRepairWorkOrder.getEmName() + "】，地点在【" + getRepairWorkOrder.getEmLocation()  + "】。",
                    2, 4, getRepairWorkOrder.getRepId(), getRepairWorkOrder.getWorkOrderCode()
            );
        }
        return DataResult.build9100();
    }

    /*
     * 验收指派人
     * */
    @Override
    public DataResult accepAssignRepair(LoginInfo loginInfo, String id, String employeeId) throws Exception {
        RepairMaintenance repairMaintenance = repairMaintenanceMapper.selectByPrimaryKey(Long.parseLong(id));
        if (repairMaintenance == null) {
            return DataResult.build9250("获取维修人员信息失败！");
        }
        if (!EnumRepState.ACCEPTED_NO.getRepState().equals(repairMaintenance.getMtcState())) {
            return DataResult.build9250("维修完成的工单才能指派验收人!");
        }
        RepairMaintenance updateRepairMaintenance = new RepairMaintenance();
        updateRepairMaintenance.setId(repairMaintenance.getId());
        updateRepairMaintenance.setMtcState(EnumRepState.ACCEPTED_YES.getRepState());
        updateRepairMaintenance.setAcceptEmployeeId(Long.parseLong(employeeId));
        updateRepairMaintenance.setDisAcceptEmployeeId(loginInfo.getLoginEmployeeId());
        repairMaintenanceMapper.updateByPrimaryKeySelective(updateRepairMaintenance);
        RepairWorkOrder updateRepairWorkOrder = new RepairWorkOrder();
        updateRepairWorkOrder.setRepId(repairMaintenance.getRepId());
        updateRepairWorkOrder.setAcceptEmployeeId(Long.parseLong(employeeId));
        updateRepairWorkOrder.setRepState(EnumRepState.ACCEPTED_YES.getRepState());
        repairWorkOrderMapper.updateByPrimaryKeySelective(updateRepairWorkOrder);

        //记录流水
        insertDisFlow(repairMaintenance.getRepId(), updateRepairMaintenance.getAcceptEmployeeId(), 3, repairMaintenance.getId(), EnumRepState.ACCEPTED_YES.getRepState(), "指定验收人员", loginInfo.getLoginEmployeeId());


        RepairWorkOrder getRepairWorkOrder = repairWorkOrderMapper.selectByPrimaryKey(repairMaintenance.getRepId());
        //待办
        commonService.insertMessageBacklog(
                updateRepairMaintenance.getAcceptEmployeeId(),
                "【"+getRepairWorkOrder.getWorkOrderCode()+"】待现场验收，请尽快处理",
                "【" + getRepairWorkOrder.getWorkOrderCode() + "】分配您进行现场验收，请尽快到场验收。维修设备：【" + getRepairWorkOrder.getEmCode() + "】-【" + getRepairWorkOrder.getEmName() + "】，地点在【" + getRepairWorkOrder.getEmLocation()  + "】。",
                2, 5, getRepairWorkOrder.getRepId(), getRepairWorkOrder.getWorkOrderCode()
        );
        return DataResult.build9100();
    }

    /*
     * 验收
     * type = 1,验收通过，2，验收驳回
     *
     * */
    @Override
    public DataResult acceptRepair(LoginInfo loginInfo, String id, String type, String acceptExplain, String acceptScore) throws Exception {
        RepairMaintenance repairMaintenance = repairMaintenanceMapper.selectByPrimaryKey(Long.parseLong(id));
        if (repairMaintenance == null) {
            return DataResult.build9250("获取维修人员信息失败！");
        }

        if (!EnumRepState.ACCEPTED_YES.getRepState().equals(repairMaintenance.getMtcState())) {
            return DataResult.build9250("待验收的工单才能提交验收!");
        }

        if (!loginInfo.getLoginEmployeeId().equals(repairMaintenance.getAcceptEmployeeId())) {
            String errName = commonService.getEmployeeNameById(repairMaintenance.getAcceptEmployeeId());
            return DataResult.build9250("人员" + errName + "才能验收操作");
        }
        RepairWorkOrder getRepairWorkOrder = repairWorkOrderMapper.selectByPrimaryKey(repairMaintenance.getRepId());
        //维修
        RepairMaintenance updateRepairMaintenance = new RepairMaintenance();
        updateRepairMaintenance.setId(repairMaintenance.getId());
        //工单
        RepairWorkOrder updateRepairWorkOrder = new RepairWorkOrder();
        updateRepairWorkOrder.setRepId(repairMaintenance.getRepId());
        //验收
        BusinessAccept businessAccept = new BusinessAccept();
        businessAccept.setSourceId(repairMaintenance.getId());
        businessAccept.setBusType(EnumAcceptBusinessType.MAINTENANCE.getBusType());
        businessAccept.setEmployeeId(loginInfo.getLoginEmployeeId());
        businessAccept.setBusEmployeeId(repairMaintenance.getEmployeeId());
        if (StrUtil.isNotBlank(acceptExplain)) {
            businessAccept.setAcceptExplain(acceptExplain);
        } else {
            businessAccept.setAcceptExplain("");
        }

        businessAccept.setAcceptTime(new Date());
        businessAccept.setCreateTime(new Date());
        int flowState = 0;
        String flowDesc = "";
        //type = 1,验收通过，2，验收驳回
        if ("1".equals(type)) {
            if(!NumberUtil.isNumber(acceptScore)){
                return DataResult.build9250("评分必须输入数字!");
            }
            businessAccept.setAcceptScore(new BigDecimal(acceptScore));
            flowState = EnumRepState.MAINTENANCE_YES.getRepState();
            flowDesc = "验收通过";
            updateRepairWorkOrder.setRepState(EnumRepState.MAINTENANCE_YES.getRepState());
            updateRepairMaintenance.setMtcState(EnumRepState.MAINTENANCE_YES.getRepState());
            businessAccept.setAcceptState(1);
            //维修时间
            Long mtcSecond = repairMaintenance.getMtcSecond();
            int estimatedWorkHour = getRepairWorkOrder.getEstimatedWorkHour();
            updateRepairWorkOrder.setWorkHourSecond(mtcSecond);
            //转换成秒
            long estimatedWorkHourSec = estimatedWorkHour * 60;
            //1未超时；2超时
            if (mtcSecond > estimatedWorkHourSec) {
                updateRepairWorkOrder.setIsTimeout(2);
            } else {
                updateRepairWorkOrder.setIsTimeout(1);
            }
        } else if ("2".equals(type)) {
            businessAccept.setAcceptScore(BigDecimal.ZERO);
            flowState = EnumRepState.MAINTENANCE_NO.getRepState();
            flowDesc = "验收驳回";
            updateRepairWorkOrder.setRepState(EnumRepState.UNDE_REPAIR.getRepState());
            updateRepairWorkOrder.setMaintenEmployeeId(repairMaintenance.getEmployeeId());
            updateRepairMaintenance.setMtcState(EnumRepState.MAINTENANCE_NO.getRepState());
            businessAccept.setAcceptState(2);

            //验收驳回新增数据
            RepairMaintenance newRepairMaintenance = new RepairMaintenance();
            newRepairMaintenance.setId(repairMaintenance.getId());
            newRepairMaintenance.setMtcDesc(repairMaintenance.getMtcDesc());
            newRepairMaintenance.setMtcFaultReason(repairMaintenance.getMtcFaultReason());
            newRepairMaintenance.setMtcFaultType(repairMaintenance.getMtcFaultType());
            newRepairMaintenance.setMtcEmState(repairMaintenance.getMtcEmState());
            newRepairMaintenance.setMtcStateDesc(repairMaintenance.getMtcStateDesc());
            newRepairMaintenance.setEmployeeId(repairMaintenance.getEmployeeId());
            newRepairMaintenance.setRepId(repairMaintenance.getRepId());
            newRepairMaintenance.setDisTime(repairMaintenance.getDisTime());
            newRepairMaintenance.setDisEmployeeId(repairMaintenance.getDisEmployeeId());
            newRepairMaintenance.setDisType(repairMaintenance.getDisType());
            newRepairMaintenance.setMtcState(EnumRepState.UNDE_REPAIR.getRepState());
            newRepairMaintenance.setMtcStartTime(repairMaintenance.getMtcStartTime());
            if (StrUtil.isBlank(repairMaintenance.getAssMtcId())) {
                newRepairMaintenance.setAssMtcId(repairMaintenance.getId() + "");
            } else {
                newRepairMaintenance.setAssMtcId(repairMaintenance.getId() + "," + repairMaintenance.getAssMtcId());
            }
            newRepairMaintenance.setProcessType(5);
            newRepairMaintenance.setCreateTime(new Date());
            newRepairMaintenance.setIsReuse(2);
            repairMaintenanceMapper.updateByPrimaryKey(newRepairMaintenance);
        }
        businessAcceptMapper.insertSelective(businessAccept);
        repairMaintenanceMapper.updateByPrimaryKeySelective(updateRepairMaintenance);
        repairWorkOrderMapper.updateByPrimaryKeySelective(updateRepairWorkOrder);

        //记录流水
        insertFlow(repairMaintenance.getRepId(), loginInfo.getLoginEmployeeId(), 4, businessAccept.getId(), flowState, flowDesc);
        //type = 1,验收通过，2，验收驳回
        if ("1".equals(type)) {
            //通知 提交人
            commonService.insertMessageInform(
                    loginInfo.getLoginEmployeeId(),
                    "【"+getRepairWorkOrder.getWorkOrderCode()+"】已维修完成，请您对维修情况进行评价",
                    "【"+getRepairWorkOrder.getWorkOrderCode()+"】已维修完成，请您对维修情况进行评价。维修设备：【" + getRepairWorkOrder.getEmCode() + "】-【" + getRepairWorkOrder.getEmName() + "】，地点在【" + getRepairWorkOrder.getEmLocation()  + "】。",
                    2, 6, getRepairWorkOrder.getRepId(), getRepairWorkOrder.getWorkOrderCode()
            );
            //通知 维修人员
            commonService.insertMessageInform(
                    repairMaintenance.getEmployeeId(),
                    "【"+getRepairWorkOrder.getWorkOrderCode()+"】已验收通过！",
                    "【"+getRepairWorkOrder.getWorkOrderCode()+"】已验收通过，验收打分【"+acceptScore+"】分。【"+acceptExplain+"】",
                    2, 6, getRepairWorkOrder.getRepId(), getRepairWorkOrder.getWorkOrderCode()
            );
        } else if("2".equals(type)){
            //待办
            commonService.insertMessageBacklog(
                    repairMaintenance.getEmployeeId(),
                    "【"+getRepairWorkOrder.getWorkOrderCode()+"】已驳回，请尽快处理。",
                    "【" + getRepairWorkOrder.getWorkOrderCode() + "】验收未通过已驳回，【"+acceptExplain+"】。请尽快处理。",
                    2, 6, getRepairWorkOrder.getRepId(), getRepairWorkOrder.getWorkOrderCode()
            );
        }
        return DataResult.build9100();
    }

    /*
     * 工单流水
     * */
    @Override
    public DataResult getWorkOrderFlow(LoginInfo loginInfo, String repId) throws Exception {
        RepairWorkOrderFlowExample flowExample = new RepairWorkOrderFlowExample();
        RepairWorkOrderFlowExample.Criteria flowCriteria = flowExample.createCriteria();
        flowCriteria.andRepIdEqualTo(Long.parseLong(repId));
        flowExample.setOrderByClause("create_time desc");
        List<RepairWorkOrderFlow> repairWorkOrderFlows = repairWorkOrderFlowMapper.selectByExample(flowExample);
        List<Map<String, Object>> flowList = new ArrayList<>();
        for (RepairWorkOrderFlow repairWorkOrderFlow : repairWorkOrderFlows) {
            Map<String, Object> map = new HashMap<>();
            map.put("sourceId", repairWorkOrderFlow.getSourceId());
            map.put("flowDesc", repairWorkOrderFlow.getFlowDesc());
            map.put("flowType", repairWorkOrderFlow.getFlowType());
            map.put("employeeName", commonService.getEmployeeNameById(repairWorkOrderFlow.getEmployeeId()));
            if (repairWorkOrderFlow.getDisEmployeeId() != 0) {
                map.put("disEmployeeName", commonService.getEmployeeNameById(repairWorkOrderFlow.getDisEmployeeId()));
            } else {
                map.put("disEmployeeName", "");
            }
            map.put("createTime", DateUtil.format(repairWorkOrderFlow.getCreateTime(), "yyyy-MM-dd HH:mm:ss"));
            flowList.add(map);
        }
        return DataResult.build9100(flowList);
    }

    @Override
    public DataResult getRepairWait(LoginInfo li, int order) throws Exception {
        List<Map<String, Object>> list = new ArrayList<>();
        if (order == 1) {
            RepairWorkOrderExample example = new RepairWorkOrderExample();
            RepairWorkOrderExample.Criteria criteria = example.createCriteria();
            criteria.andRepStateIn(Arrays.asList(3, 4, 5));
            example.setOrderByClause("create_time");
            List<RepairWorkOrder> rwoList = repairWorkOrderMapper.selectByExample(example);

            Map<Integer, String> typeRepFault = commonService.getDictMap("TYPE_REP_FAULT");
            Map<Integer, String> typeUrgencyLevel = commonService.getDictMap("TYPE_URGENCY_LEVEL");

            Map<String, List<Map<String, Object>>> dayMap = new LinkedHashMap<>();
            for (RepairWorkOrder rwo : rwoList) {
                String day = DateUtil.format(rwo.getCreateTime(), "MM-dd");
                List<Map<String, Object>> dayList = dayMap.containsKey(day) ? dayMap.get(day) : new ArrayList<>();
                Map<String, Object> map = new HashMap<>();
                map.put("id", rwo.getRepId());
                map.put("code", rwo.getWorkOrderCode());
                map.put("estimatedWorkHour", rwo.getEstimatedWorkHour());
                map.put("emName", rwo.getEmName());
                map.put("repFaultType", rwo.getRepFaultType());
                map.put("repFaultTypeName", typeRepFault.get(rwo.getRepFaultType()));
                map.put("urgencyLevel", rwo.getUrgencyLevel());
                map.put("urgencyLevelName", typeUrgencyLevel.get(rwo.getUrgencyLevel()));
                dayList.add(map);
                dayMap.put(day, dayList);
            }

            for (String key : dayMap.keySet()) {
                Map<String, Object> map = new LinkedHashMap<>();
                map.put("date", key);
                map.put("data", dayMap.get(key));
                list.add(map);
            }
        } else {

            UpkeepWorkOrderExample example = new UpkeepWorkOrderExample();
            UpkeepWorkOrderExample.Criteria criteria = example.createCriteria();
            criteria.andUpkeepStateIn(Arrays.asList(3, 4, 5));
            example.setOrderByClause("upkeep_start_time");
            List<UpkeepWorkOrder> rwoList = upkeepWorkOrderMapper.selectByExample(example);

            Map<String, List<Map<String, Object>>> dayMap = new LinkedHashMap<>();
            for (UpkeepWorkOrder uwo : rwoList) {
                String day = DateUtil.format(uwo.getUpkeepStartTime(), "MM-dd");
                List<Map<String, Object>> dayList = dayMap.containsKey(day) ? dayMap.get(day) : new ArrayList<>();
                Map<String, Object> map = new HashMap<>();
                map.put("id", uwo.getUpkeepId());
                map.put("code", uwo.getWorkOrderCode());
                map.put("estimatedWorkHour", uwo.getEstimatedWorkHour());
                map.put("emName", uwo.getEmName());
                map.put("repFaultType", null);
                map.put("repFaultTypeName", null);
                map.put("urgencyLevel", null);
                map.put("urgencyLevelName", null);
                dayList.add(map);
                dayMap.put(day, dayList);
            }

            for (String key : dayMap.keySet()) {
                Map<String, Object> map = new LinkedHashMap<>();
                map.put("date", key);
                map.put("data", dayMap.get(key));
                list.add(map);
            }
        }


        return DataResult.build9100(list);
    }

    @Override
    public DataResult getRepairEmployee(LoginInfo li, int pageNum, int pageSize, int day) throws Exception {
        Set<Integer> typeRepRoleId = commonService.getDictMap("TYPE_REP_ROLE_ID").keySet();
        long roleId = typeRepRoleId.size() > 0 ? typeRepRoleId.iterator().next() : 1L;

        Date date = new Date();
        Date beginDay = DateUtil.beginOfDay(date);
        Date endDay = DateUtil.offsetDay(DateUtil.endOfDay(date), day - 1);

        List<Map<String, Object>> list = new ArrayList<>();

        SystemUserExample suExample = new SystemUserExample();
        suExample.createCriteria().andIsDeleteEqualTo(0).andRoleIdEqualTo(roleId).andEmployeeIdNotEqualTo(0L);
        Page<SystemUser> page = PageHelper.startPage(pageNum, pageSize);
        List<SystemUser> suList = systemUserMapper.selectByExample(suExample);
        for (SystemUser su : suList) {
            List<Map<String, Object>> workList = new ArrayList<>();

            RepairWorkOrderExample rwoExample = new RepairWorkOrderExample();
            RepairWorkOrderExample.Criteria rwoCriteria = rwoExample.createCriteria();
            rwoCriteria.andRepStateIn(Arrays.asList(6, 7, 8, 9, 10, 11));
            rwoCriteria.andMaintenEmployeeIdEqualTo(su.getEmployeeId());
            rwoCriteria.andRepStartTimeBetween(beginDay, endDay);
            List<RepairWorkOrder> rwoList = repairWorkOrderMapper.selectByExample(rwoExample);
            for (RepairWorkOrder rwo : rwoList) {
                Map<String, Object> workMap = new LinkedHashMap<>();
                workMap.put("id", rwo.getRepId());
                workMap.put("order", 1);
                workMap.put("code", rwo.getWorkOrderCode());
                workMap.put("state", rwo.getRepState());
                workMap.put("estimatedWorkHour", rwo.getEstimatedWorkHour());
                workMap.put("startTime", DateUtil.formatDateTime(rwo.getRepStartTime()));
                workMap.put("endTime", DateUtil.formatDateTime(rwo.getRepEndTime() == null ? DateUtil.offsetMinute(rwo.getRepStartTime(), rwo.getEstimatedWorkHour()) : rwo.getRepEndTime()));
                workList.add(workMap);
            }
            UpkeepWorkOrderExample uwoExample = new UpkeepWorkOrderExample();
            UpkeepWorkOrderExample.Criteria uwoCriteria = uwoExample.createCriteria();
            uwoCriteria.andUpkeepStateIn(Arrays.asList(6, 7, 8, 9, 10, 11));
            uwoCriteria.andMaintenEmployeeIdEqualTo(su.getEmployeeId());
            uwoCriteria.andUpkeepStartTimeBetween(beginDay, endDay);
            List<UpkeepWorkOrder> uwoList = upkeepWorkOrderMapper.selectByExample(uwoExample);
            for (UpkeepWorkOrder uwo : uwoList) {
                Map<String, Object> workMap = new LinkedHashMap<>();
                workMap.put("id", uwo.getUpkeepId());
                workMap.put("order", 2);
                workMap.put("code", uwo.getWorkOrderCode());
                workMap.put("state", uwo.getUpkeepState());
                workMap.put("estimatedWorkHour", uwo.getEstimatedWorkHour());
                workMap.put("startTime", DateUtil.formatDateTime(uwo.getUpkeepStartTime()));
                workMap.put("endTime", DateUtil.formatDateTime(uwo.getUpkeepEndTime() == null ? DateUtil.offsetMinute(uwo.getUpkeepStartTime(), uwo.getEstimatedWorkHour()) : uwo.getUpkeepEndTime()));
                workList.add(workMap);
            }

            Map<String, Object> workerMap = new LinkedHashMap<>();
            workerMap.put("employeeId", su.getEmployeeId());
            workerMap.put("employeeName", commonService.getEmployeeNameById(su.getEmployeeId()));
            Map<String, Object> map = new LinkedHashMap<>();
            map.put("worker", workerMap);
            map.put("workList", workList);
            list.add(map);
        }
        return DataResult.build9100(new GridData(page.getTotal(), list));
    }



    @Override
    public Long findWorker(){
        try {
            Calendar calendar = Calendar.getInstance();
            int day = calendar.get(Calendar.DAY_OF_MONTH);
            Set<Integer> typeRepRoleId = commonService.getDictMap("TYPE_REP_ROLE_ID").keySet();
            long roleId = !typeRepRoleId.isEmpty() ? typeRepRoleId.iterator().next() : 1L;

            Date date = new Date();
            Date beginDay = DateUtil.beginOfDay(date);
            Date endDay = DateUtil.offsetDay(DateUtil.endOfDay(date), day - 1);
            SystemUserExample suExample = new SystemUserExample();
            suExample.createCriteria().andIsDeleteEqualTo(0).andRoleIdEqualTo(roleId).andEmployeeIdNotEqualTo(0L);
            List<SystemUser> suList = systemUserMapper.selectByExample(suExample);
            for (SystemUser su : suList) {

                RepairWorkOrderExample rwoExample = new RepairWorkOrderExample();
                RepairWorkOrderExample.Criteria rwoCriteria = rwoExample.createCriteria();
                rwoCriteria.andRepStateIn(Arrays.asList(6, 7, 11));
                rwoCriteria.andMaintenEmployeeIdEqualTo(su.getEmployeeId());
                rwoCriteria.andRepTimeBetween(beginDay, endDay);
                List<RepairWorkOrder> rwoList = repairWorkOrderMapper.selectByExample(rwoExample);

                if(rwoList.isEmpty()) {
                    UpkeepWorkOrderExample uwoExample = new UpkeepWorkOrderExample();
                    UpkeepWorkOrderExample.Criteria uwoCriteria = uwoExample.createCriteria();
                    uwoCriteria.andUpkeepStateIn(Arrays.asList(6, 7, 11));
                    uwoCriteria.andMaintenEmployeeIdEqualTo(su.getEmployeeId());
                    uwoCriteria.andUpkeepStartTimeBetween(beginDay, endDay);
                    List<UpkeepWorkOrder> uwoList = upkeepWorkOrderMapper.selectByExample(uwoExample);
                    if(uwoList.isEmpty()){
                        return su.getEmployeeId();
                    }
                }
            }
            return null;
        }catch (Exception ex){
            ex.printStackTrace();
            return null;
        }
    }



    @Override
    public DataResult updateRepairWait(LoginInfo li, int order, long id, int state, long employeeId, String startTime) throws Exception {
        if (order == 1) {
            RepairWorkOrder rwo = repairWorkOrderMapper.selectByPrimaryKey(id);
            if (state == 3) {
                rwo.setRepState(3);
                rwo.setMaintenEmployeeId(null);
                repairWorkOrderMapper.updateByPrimaryKey(rwo);

                RepairMaintenance updateRepairMaintenance = new RepairMaintenance();
                updateRepairMaintenance.setMtcState(EnumRepState.INVALID.getRepState());
                RepairMaintenanceExample rmExample = new RepairMaintenanceExample();
                rmExample.createCriteria().andRepIdEqualTo(id).andMtcStateEqualTo(6);
                repairMaintenanceMapper.updateByExampleSelective(updateRepairMaintenance, rmExample);

            } else {

                rwo.setRepState(6);
                rwo.setMaintenEmployeeId(employeeId);
                rwo.setRepStartTime(DateUtil.parseDateTime(startTime));
                repairWorkOrderMapper.updateByPrimaryKeySelective(rwo);

                RepairMaintenance newRepairMaintenance = new RepairMaintenance();
                newRepairMaintenance.setEmployeeId(employeeId);
                newRepairMaintenance.setRepId(id);
                newRepairMaintenance.setDisTime(new Date());
                newRepairMaintenance.setDisEmployeeId(li.getLoginEmployeeId());
                newRepairMaintenance.setDisType(3);
                newRepairMaintenance.setMtcState(6);
                newRepairMaintenance.setMtcStartTime(rwo.getRepStartTime());
                newRepairMaintenance.setCreateTime(new Date());
                newRepairMaintenance.setIsReuse(1);
                repairMaintenanceMapper.insertSelective(newRepairMaintenance);
            }
        } else {
            UpkeepWorkOrder uwo = upkeepWorkOrderMapper.selectByPrimaryKey(id);
            if (state == 3) {
                uwo.setUpkeepState(3);
                uwo.setMaintenEmployeeId(null);
                upkeepWorkOrderMapper.updateByPrimaryKey(uwo);

                UpkeepMaintenance updateUpkeepMaintenance = new UpkeepMaintenance();
                updateUpkeepMaintenance.setMtcState(EnumRepState.INVALID.getRepState());
                UpkeepMaintenanceExample umExample = new UpkeepMaintenanceExample();
                umExample.createCriteria().andUpkeepIdEqualTo(id).andMtcStateEqualTo(6);
                upkeepMaintenanceMapper.updateByExampleSelective(updateUpkeepMaintenance, umExample);
            } else {
                uwo.setUpkeepState(6);
                uwo.setMaintenEmployeeId(employeeId);
                uwo.setUpkeepStartTime(DateUtil.parseDateTime(startTime));
                upkeepWorkOrderMapper.updateByPrimaryKeySelective(uwo);

                UpkeepMaintenance newUpkeepMaintenance = new UpkeepMaintenance();
                newUpkeepMaintenance.setEmployeeId(employeeId);
                newUpkeepMaintenance.setUpkeepId(id);
                newUpkeepMaintenance.setDisTime(new Date());
                newUpkeepMaintenance.setDisEmployeeId(li.getLoginEmployeeId());
                newUpkeepMaintenance.setDisType(3);
                newUpkeepMaintenance.setMtcState(6);
                newUpkeepMaintenance.setMtcStartTime(uwo.getUpkeepStartTime());
                newUpkeepMaintenance.setCreateTime(new Date());
                newUpkeepMaintenance.setIsReuse(1);
                upkeepMaintenanceMapper.insertSelective(newUpkeepMaintenance);
            }
        }
        return DataResult.build9100();
    }

    private RepairWorkOrder getNewRepairWorkOrder(RepairWorkOrderDto repairDto) {
        RepairWorkOrder record = new RepairWorkOrder();
        record.setRepFaultType(Integer.parseInt(repairDto.getRepFaultType()));
        record.setUrgencyLevel(Integer.parseInt(repairDto.getUrgencyLevel()));
        record.setRepEmState(Integer.parseInt(repairDto.getRepEmState()));
        record.setWorkOrderCode(getWorkOrderCode());
        record.setRepState(EnumRepState.PENDING_ANNOUNCE.getRepState());
        record.setRepStartTime(new Date());
        record.setCreateTime(new Date());
        if (StrUtil.isNotBlank(repairDto.getEmStateDesc())) {
            record.setEmStateDesc(repairDto.getEmStateDesc());
        } else {
            record.setEmStateDesc("");
        }
        if (StrUtil.isNotBlank(repairDto.getRepDesc())) {
            record.setRepDesc(repairDto.getRepDesc());
        } else {
            record.setRepDesc("");
        }
        return record;
    }

    /*
     * 审核信息查询
     * */
    private void addAnnounce(Map<String, Object> map, RepairWorkOrder repairWorkOrder) {
        Map<String, Object> announceMap = getAnnounceMap(repairWorkOrder.getRepId());
        map.put("announceMap", announceMap);
    }

    /*
     * 审核和派生信息
     * */
    private RepairMaintenance addAllocatedAnn(Map<String, Object> map, RepairWorkOrder repairWorkOrder) {
        Map<String, Object> announceMap = getAnnounceMap(repairWorkOrder.getRepId());
        RepairMaintenanceExample repMainExample = new RepairMaintenanceExample();
        RepairMaintenanceExample.Criteria repMainCriteria = repMainExample.createCriteria();
        repMainCriteria.andRepIdEqualTo(repairWorkOrder.getRepId());
        repMainCriteria.andMtcStateEqualTo(repairWorkOrder.getRepState());
        repMainExample.setOrderByClause("create_time desc limit 1");
        List<RepairMaintenance> repairMaintenanceList = repairMaintenanceMapper.selectByExample(repMainExample);
        if (CollUtil.isEmpty(repairMaintenanceList)) {
            return null;
        }

        RepairMaintenance repairMaintenance = repairMaintenanceList.get(0);
        announceMap.put("disTime", DateUtil.format(repairMaintenance.getDisTime(), "yyyy-MM-dd HH:mm:ss"));
        //维修人员
        if (repairMaintenance.getDisType() == 1) {
            announceMap.put("disEmployeeName", "系统自动分配");
        } else if (repairMaintenance.getDisType() == 2) {
            String disEmployeeName = commonService.getEmployeeNameById(repairMaintenance.getDisEmployeeId());
            if (StrUtil.isNotBlank(disEmployeeName)) {
                announceMap.put("disEmployeeName", disEmployeeName + "自己领取");
            } else {
                announceMap.put("disEmployeeName", "");
            }
        } else if (repairMaintenance.getDisType() == 3) {
            announceMap.put("disEmployeeName", commonService.getEmployeeNameById(repairMaintenance.getDisEmployeeId()));
        } else {
            announceMap.put("disEmployeeName", "");
        }
        map.put("announceMap", announceMap);
        return repairMaintenance;
    }

    /*
     * 已分配和维修中展示数据
     * */
    private void addAllocated(LoginInfo loginInfo, Map<String, Object> map, RepairWorkOrder repairWorkOrder) {
        RepairMaintenance repairMaintenance = addAllocatedAnn(map, repairWorkOrder);
        if (repairMaintenance != null) {
            Map<String, Object> maintenanceMap = new HashMap<>();
            maintenanceMap.put("employeeName", commonService.getEmployeeNameById(repairMaintenance.getEmployeeId()));
            maintenanceMap.put("id", repairMaintenance.getId());
            if (loginInfo.getLoginEmployeeId().equals(repairMaintenance.getEmployeeId())) {
                maintenanceMap.put("flag", true);
            } else {
                maintenanceMap.put("flag", false);
            }
            maintenanceMap.put("disType", repairMaintenance.getDisType());
            maintenanceMap.put("isReuse", repairMaintenance.getIsReuse());

            if (!repairWorkOrder.getRepState().equals(EnumRepState.ALLOCATED.getRepState())) {
                maintenanceMap.put("mtcStartTime", DateUtil.format(repairMaintenance.getMtcStartTime(), "yyyy-MM-dd HH:mm:ss"));
            }
            map.put("maintenanceMap", maintenanceMap);
        }
    }

    /*
     * 待验收
     * */
    private RepairMaintenance addAccepted(LoginInfo loginInfo, Map<String, Object> map, RepairWorkOrder repairWorkOrder) {
        RepairMaintenance repairMaintenance = addAllocatedAnn(map, repairWorkOrder);
        if (repairMaintenance == null) {
            return repairMaintenance;
        }
        Map<String, Object> maintenanceMap = new HashMap<>();
        maintenanceMap.put("employeeName", commonService.getEmployeeNameById(repairMaintenance.getEmployeeId()));
        maintenanceMap.put("id", repairMaintenance.getId());
        maintenanceMap.put("mtcEmState", repairMaintenance.getMtcEmState());
        maintenanceMap.put("mtcStateDesc", repairMaintenance.getMtcStateDesc());
        maintenanceMap.put("mtcFaultType", repairMaintenance.getMtcFaultType());
        maintenanceMap.put("mtcFaultReason", repairMaintenance.getMtcFaultReason());
        maintenanceMap.put("mtcDesc", repairMaintenance.getMtcDesc());
        maintenanceMap.put("mtcEndTime", DateUtil.format(repairMaintenance.getMtcEndTime(), "yyyy-MM-dd HH:mm:ss"));
        long mtcSecond = repairMaintenance.getMtcSecond();

        RepairMaintenanceSuspendExample supendExample = new RepairMaintenanceSuspendExample();
        RepairMaintenanceSuspendExample.Criteria supendCriteria = supendExample.createCriteria();
        supendCriteria.andMaintenanceIdEqualTo(repairMaintenance.getId());
        supendCriteria.andStateEqualTo(2);
        List<RepairMaintenanceSuspend> repairMaintenanceSuspends = repairMaintenanceSuspendMapper.selectByExample(supendExample);
        long suspendSecond = 0;
        for (RepairMaintenanceSuspend suspendInfo : repairMaintenanceSuspends) {
            if (suspendInfo.getSuspendSecond() != 0) {
                suspendSecond += suspendInfo.getSuspendSecond();
            }
        }

        //计算后维修的时间
        long countMtcSecond = mtcSecond - suspendSecond;

        if (countMtcSecond <= 0) {
            maintenanceMap.put("mtcSecond", "");
        } else {
            long second = countMtcSecond % 60;
            long minutes = TimeUnit.SECONDS.toMinutes(countMtcSecond);
            if (minutes == 0) {
                maintenanceMap.put("mtcSecond", second + "秒");
            } else if (second == 0) {
                maintenanceMap.put("mtcSecond", minutes + "分");
            } else {
                maintenanceMap.put("mtcSecond", minutes + "分" + second + "秒");
            }
        }
        if (suspendSecond == 0) {
            maintenanceMap.put("suspendSecond", "无");
        } else {
            maintenanceMap.put("suspendSecond", suspendSecond + "秒");
        }
        if (repairWorkOrder.getRepState().equals(EnumRepState.ACCEPTED_YES.getRepState())) {
            if (loginInfo.getLoginEmployeeId().equals(repairMaintenance.getAcceptEmployeeId())) {
                maintenanceMap.put("acceptFlag", true);
            } else {
                maintenanceMap.put("acceptFlag", false);
            }
        }
        getMaintenanceFileList(maintenanceMap, repairMaintenance.getId());
        map.put("maintenanceCompleteMap", maintenanceMap);
        return repairMaintenance;
    }

    /*
     * 验收信息展示
     * */
    private void addAccept(Map<String, Object> map, RepairMaintenance repairMaintenance) {
        Map<String, Object> acceptMap = new HashMap<>();
        BusinessAcceptExample accExample = new BusinessAcceptExample();
        BusinessAcceptExample.Criteria accCriteria = accExample.createCriteria();
        accCriteria.andSourceIdEqualTo(repairMaintenance.getId());
        accCriteria.andBusTypeEqualTo(EnumBusinessType.MAINTENANCE.getBusType());
        accExample.setOrderByClause("create_time desc limit 1");
        List<BusinessAccept> businessAccepts = businessAcceptMapper.selectByExample(accExample);
        if (CollUtil.isNotEmpty(businessAccepts)) {
            BusinessAccept businessAccept = businessAccepts.get(0);
            if (1 == businessAccept.getAcceptState()) {
                acceptMap.put("acceptStateName", "验收通过");
            } else if (2 == businessAccept.getAcceptState()) {
                acceptMap.put("acceptStateName", "验收驳回");
            }
            acceptMap.put("employeeName", commonService.getEmployeeNameById(businessAccept.getEmployeeId()));
            acceptMap.put("acceptExplain", businessAccept.getAcceptExplain());
            acceptMap.put("acceptScore", businessAccept.getAcceptScore());
            acceptMap.put("acceptTime", DateUtil.format(businessAccept.getAcceptTime(), "yyyy-MM-dd HH:mm:ss"));
        }
        map.put("acceptMap", acceptMap);
    }


    //审核信息MAP
    private Map<String, Object> getAnnounceMap(Long repId) {
        Map<String, Object> announceMap = new HashMap<>();
        BusinessAnnounceExample busExample = new BusinessAnnounceExample();
        BusinessAnnounceExample.Criteria busCriteria = busExample.createCriteria();
        busCriteria.andSourceIdEqualTo(repId);
        busCriteria.andBusTypeEqualTo(EnumAnnBusinessType.REPAIR.getBusType());
        busExample.setOrderByClause("create_time desc limit 1");
        List<BusinessAnnounce> businessAnnounces = businessAnnounceMapper.selectByExample(busExample);
        if (CollUtil.isNotEmpty(businessAnnounces)) {
            BusinessAnnounce businessAnnounce = businessAnnounces.get(0);
            //1审核通过；0审核驳回
            if (businessAnnounce.getAnnState() == 1) {
                announceMap.put("annStateName", "审核通过");
            } else {
                announceMap.put("annStateName", "审核驳回");
            }
            announceMap.put("annState", businessAnnounce.getAnnState());
            announceMap.put("annExplain", businessAnnounce.getAnnExplain());
            announceMap.put("annTime", DateUtil.format(businessAnnounce.getAnnTime(), "yyyy-MM-dd HH:mm:ss"));
            announceMap.put("employeeName", commonService.getEmployeeNameById(businessAnnounce.getEmployeeId()));
        }
        return announceMap;
    }

    private void insertWorkOrderFile(Long busTablesId, Long employeeId, String fileCode, int busType, int fileGroup, int fileType) {
        BusinessFile businessFile = new BusinessFile();
        businessFile.setBusTablesId(busTablesId);
        businessFile.setBusType(busType);
        businessFile.setFileGroup(fileGroup);
        businessFile.setEmployeeId(employeeId);
        businessFile.setFileCode(fileCode);
        businessFile.setFileType(fileType);
        businessFile.setCreateTime(new Date());
        businessFileMapper.insertSelective(businessFile);
    }

    private void insertMaintenanceFile(Long busTablesId, Long employeeId, RepairMaintenanceDto repairMaintenanceDto) {
        //旧的上传图片
        if (StrUtil.isNotBlank(repairMaintenanceDto.getFileOldPicCode())) {
            if (repairMaintenanceDto.getFileOldPicCode().contains(",")) {
                String[] split = repairMaintenanceDto.getFileOldPicCode().split(",");
                for (String spCode : split) {
                    insertWorkOrderFile(busTablesId, employeeId, spCode, EnumBusinessType.MAINTENANCE.getBusType(), 2, 1);
                }
            } else {
                insertWorkOrderFile(busTablesId, employeeId, repairMaintenanceDto.getFileOldPicCode(), EnumBusinessType.MAINTENANCE.getBusType(), 2, 1);

            }
        }
        //旧的上传音频
        if (StrUtil.isNotBlank(repairMaintenanceDto.getFileOldAudioCode())) {
            if (repairMaintenanceDto.getFileOldAudioCode().contains(",")) {
                String[] split = repairMaintenanceDto.getFileOldAudioCode().split(",");
                for (String spCode : split) {
                    insertWorkOrderFile(busTablesId, employeeId, spCode, EnumBusinessType.MAINTENANCE.getBusType(), 2, 2);
                }
            } else {
                insertWorkOrderFile(busTablesId, employeeId, repairMaintenanceDto.getFileOldAudioCode(), EnumBusinessType.MAINTENANCE.getBusType(), 2, 2);
            }
        }
        //旧的上传视频
        if (StrUtil.isNotBlank(repairMaintenanceDto.getFileOldVideoCode())) {
            if (repairMaintenanceDto.getFileOldVideoCode().contains(",")) {
                String[] split = repairMaintenanceDto.getFileOldVideoCode().split(",");
                for (String spCode : split) {
                    insertWorkOrderFile(busTablesId, employeeId, spCode, EnumBusinessType.MAINTENANCE.getBusType(), 2, 3);
                }
            } else {
                insertWorkOrderFile(busTablesId, employeeId, repairMaintenanceDto.getFileOldVideoCode(), EnumBusinessType.MAINTENANCE.getBusType(), 2, 3);
            }
        }
        //新的上传图片
        if (StrUtil.isNotBlank(repairMaintenanceDto.getFileNewPicCode())) {
            if (repairMaintenanceDto.getFileNewPicCode().contains(",")) {
                String[] split = repairMaintenanceDto.getFileNewPicCode().split(",");
                for (String spCode : split) {
                    insertWorkOrderFile(busTablesId, employeeId, spCode, EnumBusinessType.MAINTENANCE.getBusType(), 3, 1);
                }
            } else {
                insertWorkOrderFile(busTablesId, employeeId, repairMaintenanceDto.getFileNewPicCode(), EnumBusinessType.MAINTENANCE.getBusType(), 3, 1);
            }
        }
        //新的上传音频
        if (StrUtil.isNotBlank(repairMaintenanceDto.getFileNewAudioCode())) {
            if (repairMaintenanceDto.getFileNewAudioCode().contains(",")) {
                String[] split = repairMaintenanceDto.getFileNewAudioCode().split(",");
                for (String spCode : split) {
                    insertWorkOrderFile(busTablesId, employeeId, spCode, EnumBusinessType.MAINTENANCE.getBusType(), 3, 2);
                }
            } else {
                insertWorkOrderFile(busTablesId, employeeId, repairMaintenanceDto.getFileNewAudioCode(), EnumBusinessType.MAINTENANCE.getBusType(), 3, 2);
            }
        }
        //新的上传视频
        if (StrUtil.isNotBlank(repairMaintenanceDto.getFileNewVideoCode())) {
            if (repairMaintenanceDto.getFileNewVideoCode().contains(",")) {
                String[] split = repairMaintenanceDto.getFileNewVideoCode().split(",");
                for (String spCode : split) {
                    insertWorkOrderFile(busTablesId, employeeId, spCode, EnumBusinessType.MAINTENANCE.getBusType(), 3, 3);
                }
            } else {
                insertWorkOrderFile(busTablesId, employeeId, repairMaintenanceDto.getFileNewVideoCode(), EnumBusinessType.MAINTENANCE.getBusType(), 3, 3);
            }
        }
    }

    private void getRepairFileList(Map<String, Object> map, Long busTablesId) {
        List<BusinessFileVo> businessFileList = businessFileDao.selectBusinessFileByCodes(busTablesId, EnumBusinessType.REPAIR.getBusType());
        List<Map<String, String>> picList = new ArrayList<>();
        List<Map<String, String>> audioList = new ArrayList<>();
        List<Map<String, String>> videoList = new ArrayList<>();
        int i = 1;
        for (BusinessFileVo vo : businessFileList) {
            //fileType： 1,图片pic,2音频audio，3，视频video'
            if (1 == vo.getFileType()) {
                Map<String, String> picMap = new HashMap<>();
                picMap.put("fileCode", vo.getFileCode());
                picMap.put("fileName", vo.getFileName());
                picList.add(picMap);
            } else if (2 == vo.getFileType()) {
                Map<String, String> audioMap = new HashMap<>();
                audioMap.put("fileCode", vo.getFileCode());
                if (StrUtil.isBlank(vo.getFileName())) {
                    audioMap.put("fileName", "");
                } else {
                    audioMap.put("fileName", "音频" + i + vo.getFileName().substring(vo.getFileName().lastIndexOf(".")));
                }
                audioList.add(audioMap);
                i++;
            } else if (3 == vo.getFileType()) {
                Map<String, String> videoMap = new HashMap<>();
                videoMap.put("fileCode", vo.getFileCode());
                videoMap.put("fileName", vo.getFileName());
                videoList.add(videoMap);
            }
        }
        map.put("picList", picList);
        map.put("audioList", audioList);
        map.put("videoList", videoList);
    }

    private void getMaintenanceFileList(Map<String, Object> map, Long busTablesId) {
        List<BusinessFileVo> businessFileList = businessFileDao.selectBusinessFileByCodes(busTablesId, EnumBusinessType.MAINTENANCE.getBusType());

        List<Map<String, String>> picOldList = new ArrayList<>();
        List<Map<String, String>> audioOldList = new ArrayList<>();
        List<Map<String, String>> videoOldList = new ArrayList<>();
        List<Map<String, String>> picNewList = new ArrayList<>();
        List<Map<String, String>> audioNewList = new ArrayList<>();
        List<Map<String, String>> videoNewList = new ArrayList<>();
        int i = 1;
        int j = 1;
        for (BusinessFileVo vo : businessFileList) {
            /*
             * FileGroup: 2,维修前的文件，3，维修后的文件
             * fileType： 1,图片pic,2音频audio，3，视频video'
             * */
            if (vo.getFileGroup() == 2) {
                if (1 == vo.getFileType()) {
                    Map<String, String> picOldMap = new HashMap<>();
                    picOldMap.put("fileCode", vo.getFileCode());
                    picOldMap.put("fileName", vo.getFileName());
                    picOldList.add(picOldMap);
                } else if (2 == vo.getFileType()) {
                    Map<String, String> audioOldMap = new HashMap<>();
                    audioOldMap.put("fileCode", vo.getFileCode());
                    if (StrUtil.isBlank(vo.getFileName())) {
                        audioOldMap.put("fileName", "");
                    } else {
                        audioOldMap.put("fileName", "音频" + i + vo.getFileName().substring(vo.getFileName().lastIndexOf(".")));
                    }
                    audioOldList.add(audioOldMap);
                    i++;
                } else if (3 == vo.getFileType()) {
                    Map<String, String> videoOldMap = new HashMap<>();
                    videoOldMap.put("fileCode", vo.getFileCode());
                    videoOldMap.put("fileName", vo.getFileName());
                    videoOldList.add(videoOldMap);
                }
            } else if (vo.getFileGroup() == 3) {
                if (1 == vo.getFileType()) {
                    Map<String, String> picNewMap = new HashMap<>();
                    picNewMap.put("fileCode", vo.getFileCode());
                    picNewMap.put("fileName", vo.getFileName());
                    picNewList.add(picNewMap);
                } else if (2 == vo.getFileType()) {
                    Map<String, String> audioNewMap = new HashMap<>();
                    audioNewMap.put("fileCode", vo.getFileCode());

                    if (StrUtil.isBlank(vo.getFileName())) {
                        audioNewMap.put("fileName", "");
                    } else {
                        audioNewMap.put("fileName", "音频" + j + vo.getFileName().substring(vo.getFileName().lastIndexOf(".")));
                    }
                    audioNewList.add(audioNewMap);
                    j++;
                } else if (3 == vo.getFileType()) {
                    Map<String, String> videoNewMap = new HashMap<>();
                    videoNewMap.put("fileCode", vo.getFileCode());
                    videoNewMap.put("fileName", vo.getFileName());
                    videoNewList.add(videoNewMap);
                }
            }
        }
        map.put("picOldList", picOldList);
        map.put("audioOldList", audioOldList);
        map.put("videoOldList", videoOldList);
        map.put("picNewList", picNewList);
        map.put("audioNewList", audioNewList);
        map.put("videoNewList", videoNewList);
    }

    private void insertFlow(Long repId, Long employeeId, int flowType, Long sourceId, Integer state, String flowDesc) {
        RepairWorkOrderFlow workOrderFlow = new RepairWorkOrderFlow();
        workOrderFlow.setRepId(repId);
        workOrderFlow.setEmployeeId(employeeId);
        workOrderFlow.setSourceId(sourceId);
        workOrderFlow.setDisEmployeeId(0L);
        workOrderFlow.setFlowDesc(flowDesc);
        workOrderFlow.setFlowType(flowType);
        workOrderFlow.setState(state);
        workOrderFlow.setCreateTime(new Date());
        repairWorkOrderFlowMapper.insert(workOrderFlow);
    }

    private void insertDisFlow(Long repId, Long employeeId, int flowType, Long sourceId, Integer state, String flowDesc, Long disEmployeeId) {
        RepairWorkOrderFlow workOrderFlow = new RepairWorkOrderFlow();
        workOrderFlow.setRepId(repId);
        workOrderFlow.setEmployeeId(employeeId);
        workOrderFlow.setSourceId(sourceId);
        workOrderFlow.setDisEmployeeId(disEmployeeId);
        workOrderFlow.setFlowDesc(flowDesc);
        workOrderFlow.setFlowType(flowType);
        workOrderFlow.setState(state);
        workOrderFlow.setCreateTime(new Date());
        repairWorkOrderFlowMapper.insert(workOrderFlow);
    }

    /*
     * 获取工单号
     * */
    private String getWorkOrderCode() {
        String format = DateUtil.format(new Date(), DatePattern.PURE_DATE_FORMATTER);
        RepairWorkOrderExample example = new RepairWorkOrderExample();
        RepairWorkOrderExample.Criteria criteria = example.createCriteria();
        criteria.andCreateTimeGreaterThanOrEqualTo(DateUtil.parseDate(DateUtil.today()));
        long l = repairWorkOrderMapper.countByExample(example);
        l += 1;
        String index = String.valueOf(l);
        if (index.length() == 1) {
            index = "00" + index;
        } else if (index.length() == 2) {
            index = "0" + index;
        }
        String workOrderCode = "wx" + format + index;
        return workOrderCode;
    }

    private String getTimeStr(long timeSecond) {
        String strTimeSecond = "";
        long second = timeSecond % 60;
        long minutes = TimeUnit.SECONDS.toMinutes(timeSecond);
        if (minutes == 0) {
            strTimeSecond = second + "秒";
        } else if (second == 0) {
            strTimeSecond = minutes + "分";
        } else {
            strTimeSecond = minutes + "分" + second + "秒";
        }
        return strTimeSecond;
    }

    private String getStatieName(int state) {
        String stateName = "";
        if (1 == state) {
            stateName = "失效";
        } else if (2 == state) {
            stateName = "待审核";
        }
        return stateName;
    }
}
